Skip to content

Commit

Permalink
Solved cache invalidation problem when user do paginate
Browse files Browse the repository at this point in the history
  • Loading branch information
riadelimemmedov committed Feb 28, 2024
1 parent 59ecd36 commit ceb6242
Show file tree
Hide file tree
Showing 3 changed files with 19 additions and 5 deletions.
9 changes: 9 additions & 0 deletions backend/apps/pet/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,3 +5,12 @@
# !PetPagination
class PetPagination(PageNumberPagination):
page_size = 2 # Set the number of items per page
cursor_query_param = "page"

def get_paginated_response(self, data):
return Response(
{
"count": self.page.paginator.count,
"pets": data,
}
)
1 change: 1 addition & 0 deletions backend/apps/pet/serializers.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
class PetSerializer(serializers.ModelSerializer):
# created = serializers.DateTimeField(format="%Y-%m-%d")
# modified = serializers.DateTimeField(format="%Y-%m-%d")
# obj_count = serializers.SerializerMethodField()

class Meta:
model = Pet
Expand Down
14 changes: 9 additions & 5 deletions backend/apps/pet/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -34,18 +34,22 @@ def get(self, request):
Response: A response object containing the serialized data of all pets and the HTTP status code.
"""
pet_objects = cache.get("pet_objects")
pet_count = cache.get("pet_count")
page_number = cache.get("page_number")
paginator = self.pagination_class() # Use the desired pagination class

page_number = request.query_params.get("page")
print("Page number ", page_number)
page = request.query_params.get("page")

if pet_objects is None:
if pet_objects is None or pet_count is None or page_number != page:
pet_objects = paginator.paginate_queryset(Pet.objects.all(), request)
pet_count = Pet.objects.count()
cache.set("pet_objects", pet_objects, 60 * 3)
cache.set("pet_count", pet_count, 60 * 3)
cache.set("page_number", page, 60 * 3)

# pet_objects = Pet.objects.all()
serializer = self.serializer_class(pet_objects, many=True)
return Response(serializer.data, status=status.HTTP_200_OK)
response_data = {"pet_count": pet_count, "pet_objects": serializer.data}
return Response(response_data, status=status.HTTP_200_OK)

def post(self, request, format=None):
"""
Expand Down

0 comments on commit ceb6242

Please sign in to comment.