You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Django Rest API分页重复展示相同条目问题求助

Troubleshooting Your Django Rest API Pagination Issue

Hey there! Let's dig into this pagination problem you're dealing with—duplicate entries across the first few pages, inconsistent item counts per page, and the same pattern repeating later is super frustrating, but it's usually tied to a couple of common issues. Let's break it down:

1. You're Missing a Stable, Unique Sort Key

This is the #1 culprit for duplicate pagination results in Django. Here's why:
When you use pagination (either manually or via DRF), the ORM relies on a consistent order of your queryset to calculate offsets correctly. If you don't specify an .order_by() clause, or your sort field has duplicate values (like multiple entries with the same created_at timestamp), the database can't guarantee a fixed order of results. That means when you fetch page 2, the database might return the same set of rows as page 1 because it doesn't have a unique way to sort them.

Fix It:

Add a unique secondary sort key to your queryset—usually the model's primary key (id) works perfectly. For example:

queryset = ModelA.objects.filter(project_id=project_id).order_by('created_at', 'id')

The id ensures that even if two entries have the same created_at, they'll always be ordered consistently, so pagination offsets work as expected.

2. Manual Pagination Logic Has Errors

Since you're using APIView instead of DRF's generic views, I'm guessing you're handling pagination manually (calculating offsets, slicing the queryset, etc.). It's easy to mess up the math here—like miscalculating offset = (page_number - 1) * page_size, or using a page number that's being parsed incorrectly from the request.

Fix It:

Ditch the manual calculations and use DRF's built-in pagination classes. They're tested, reliable, and take care of all the edge cases. Here's how to set it up:
First, define a pagination class:

from rest_framework.pagination import PageNumberPagination

class ModelAPagination(PageNumberPagination):
    page_size = 10  # Default page size
    page_size_query_param = 'page_size'  # Let users override if needed
    max_page_size = 100  # Prevent huge pages

Then update your API view:

class ModelAFilterAPI(APIView):
    def get(self, request, project_id, sea...):  # Fill in your filter logic here
        # Build your queryset WITH a stable sort
        queryset = ModelA.objects.filter(project_id=project_id).order_by('id')
        # Apply pagination
        paginator = ModelAPagination()
        paginated_queryset = paginator.paginate_queryset(queryset, request)
        # Serialize and return the paginated response
        serializer = ModelASerializer(paginated_queryset, many=True)
        return paginator.get_paginated_response(serializer.data)

DRF will automatically handle the page query parameter, offset calculations, and return the correct count/next/previous links in the response.

3. Filter Logic Is Causing Inconsistent Querysets

The truncated sea... in your code hints at a search/filter component. If your filter logic is dynamic (e.g., relying on request parameters that change unexpectedly, or using fuzzy matching that returns different results on each page load), it can break pagination consistency.

Fix It:

Debug your queryset by printing the generated SQL to make sure it's consistent across page requests. Add this line right after you build your queryset:

print(queryset.query)

Run your API and check the console—if the SQL changes between page 1 and page 2, your filter logic is the problem. Double-check how you're parsing search parameters (like request.GET.get('sea')) to ensure they're being handled consistently.


Start with the sort key fix first—it's the most common solution for this exact problem. If that doesn't work, move to switching to DRF's built-in pagination, then debug your filter logic.

内容的提问来源于stack exchange,提问作者M.Izzat

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:07:11