whitebear
whitebear

Reputation: 12423

Clear each view cache

I have a few views each has cache table.

And deleting cache when pre_save callback.

For now I delete every cache, everytime.

Is there any way to delete each tables one by one???

class ArticleViewSet(viewsets.ModelViewSet):
    queryset = Article.objects.all()
    @method_decorator(cache_page(None))
    @method_decorator(vary_on_cookie)
    def list(self,request,*args,**kwargs):

class ItemViewSet(viewsets.ModelViewSet):
    queryset = Item.objects.all()
    @method_decorator(cache_page(None))
    @method_decorator(vary_on_cookie)
    def list(self,request,*args,**kwargs):

@receiver(pre_save, sender=Article)
def cache_delete_callback(sender, **kwargs):
    print("cache delete")
    from django.core.cache import cache;cache.clear()// want to delete only Article cache

@receiver(pre_save, sender=Item)
def cache_delete_tweet_callback(sender, **kwargs):
    print("clear tweet cache")
    from django.core.cache import cache;cache.clear() // wan to delete only Item Cache

Upvotes: 0

Views: 267

Answers (1)

iklinac
iklinac

Reputation: 15728

Your cache is set on pages(views) not on single object, as from documentation

The per-view cache, like the per-site cache, is keyed off of the URL. If multiple URLs point at the same view, each URL will be cached separately. Continuing the my_view example, if your URLconf looks like this:

urlpatterns = [ path('foo//', my_view), ] then requests to /foo/1/ and /foo/23/ will be cached separately, as you may expect. But once a particular URL (e.g., /foo/23/) has been requested, subsequent requests to that URL will use the cache.

It is visible that cache keys are in fact URL paths, so you can delete each of them by using cache.delete(key) where key is URL. So something in a line of following

cache.delete(
    reverse(view_name, args=[item_id]
)

Upvotes: 1

Related Questions