Django Rest Framework: How to Handle Pagination When Filtering Foreign Key Relationships?
Does anyone know how to I've been banging my head against this for hours. I've been banging my head against this for hours. I'm working with Django Rest Framework (DRF) version 3.12.2 and trying to implement pagination on a filtered queryset that involves foreign key relationships. My API endpoint is designed to return a list of `Orders` that belong to a specific `Customer`. Initially, I used the default pagination but realized that it doesn't handle filtering effectively when the number of related records is large. Here's a simplified version of my view: ```python from rest_framework import viewsets from rest_framework.pagination import PageNumberPagination from .models import Order, Customer from .serializers import OrderSerializer class StandardResultsSetPagination(PageNumberPagination): page_size = 10 class OrderViewSet(viewsets.ModelViewSet): queryset = Order.objects.all() serializer_class = OrderSerializer pagination_class = StandardResultsSetPagination def get_queryset(self): customer_id = self.request.query_params.get('customer_id', None) if customer_id is not None: return self.queryset.filter(customer_id=customer_id) return self.queryset ``` When I try to access the endpoint with a filter like `/api/orders/?customer_id=1`, I get the expected results, but the pagination information in the response seems to reflect the total number of `Orders` instead of just those belonging to the specified customer. Here's the pagination response: ```json { "count": 100, "next": "http://example.com/api/orders/?customer_id=1&page=2", "previous": null, "results": [ {...}, {...} ] } ``` The `count` field indicates that there are 100 total orders, not just the 10 associated with `customer_id=1`. How can I modify my view to ensure that the pagination reflects the filtered queryset instead of the entire queryset? I tried overriding the `get_paginated_response` method but still ran into issues. Any guidance or examples would be greatly appreciated! Thanks in advance! I'm working on a service that needs to handle this. What am I doing wrong? For reference, this is a production REST API.