Sobes.tech
Junior — Middle

Можно ли использовать BaseViews с вызовом через get, чтобы сохранять состояние в свойстве для реализации кэширования?

sobes.tech AI

Answer from AI

In Django Class-Based Views (CBV), including BaseView, it is not recommended to store state in instance properties for caching if you are using the get method to handle requests. This is because each HTTP request creates a new view instance, and state is not preserved between requests.

If caching needs to be implemented, it is better to use external mechanisms, such as:

  • Caching at the Django cache framework level (memcached, redis, etc.)
  • Caching decorators, such as @cache_page
  • Caching in the database or filesystem

Example of using caching with a decorator:

from django.views.generic import View
from django.utils.decorators import method_decorator
from django.views.decorators.cache import cache_page

class MyView(View):
    @method_decorator(cache_page(60*15))  # cache for 15 minutes
    def get(self, request, *args, **kwargs):
        # heavy logic
        return HttpResponse('Result')

Thus, storing state in view properties for caching is inefficient and does not align with the view's lifecycle in Django.

Можно ли использовать BaseViews с вызовом через get… - sobes.tech