chibisov / drf-extensions

DRF-extensions is a collection of custom extensions for Django REST Framework
http://chibisov.github.io/drf-extensions/docs
MIT License
1.47k stars 208 forks source link

CacheResponseMixin does not work with pagination #160

Closed jkblgithub closed 8 years ago

jkblgithub commented 8 years ago

I have added CacheResponseMixin to my viewset, but only the first page is cached and returned for all other pages e.g. /?page=2 simply returns the results for page 1.

My code:
class ProductViewSet(CacheResponseMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    queryset = Product.objects.filter(withdrawn=False)
    serializer_class = ProductSerializer
    pagination_class = LargeResultsSetPagination

I am using django 1.85. Is this a bug or am I missing something please?

ghost commented 8 years ago

I had the same problem on Django 1.9.9 with drf-extensions 0.2.8.

The default list cache key function uses PaginationKeyBit. I am thinking something must not be working with the PaginationKeyBit class. What I did that has been working for me is make a custom list cache key function which also uses the QueryParamsKeyBit class.

jkblgithub commented 8 years ago

@jbsag Thanks. I did what you suggested and all is working well now. For anyone who might be interested, this is the code I used:

from rest_framework_extensions.cache.mixins import CacheResponseMixin
from rest_framework_extensions.key_constructor.constructors import (
    DefaultKeyConstructor
)
from rest_framework_extensions.key_constructor.bits import (
    QueryParamsKeyBit   
)

class QueryParamsKeyConstructor(DefaultKeyConstructor):
    all_query_params = bits.QueryParamsKeyBit()

class ProductViewSet(CacheResponseMixin, mixins.ListModelMixin, mixins.RetrieveModelMixin, viewsets.GenericViewSet):
    queryset = Product.objects.filter(withdrawn=False)
    serializer_class = ProductSerializer
    pagination_class = LargeResultsSetPagination
    list_cache_key_func = QueryParamsKeyConstructor()