How to cache dynamic content with signal-based caching?

I have an expense tracker application where I display a list of expense categories which can be changed by user. So I'm trying to cache the data as follows:

class ShowCategories(LoginRequiredMixin, ListView):
    paginate_by = 10
    model = Category
    context_object_name = 'categories'
    template_name = 'expense_tracker/category_list.html'

    def get_queryset(self):
        category = cache.get('category')
        if category is None:
            category = Category.objects.filter(user=self.request.user)
            cache.set('category', category)
        return category

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = 'Категории'
        return context

And I use signals to invalidate the cache:

@receiver(post_delete, sender=Category)
def category_post_delete_handler(sender, **kwargs):
    cache.delete('category')


@receiver(post_save, sender=Category)
def category_post_save_handler(sender, **kwargs):
    cache.delete('category')

But the page displays new categories only after deleting one of the old categories. How can I fix this?

Back to Top