HTML 原文 · 完整 Markdown · 纯文本 · 分段目录 · ← 上一段 · 下一段 →

03-API和序列化器(Serializers)

第 39 / 78 段:查询列表 API(返回列表数据的 API)

Django 风格指南 (HackSoft) · 发布 2026-02-05 · 更新 2026-11-11 · 标签:Django、DRF、API设计

查询列表 API(返回列表数据的 API)(续)

from collections import OrderedDict

from rest_framework.pagination import LimitOffsetPagination as _LimitOffsetPagination
from rest_framework.response import Response

class LimitOffsetPagination(_LimitOffsetPagination):
    default_limit = 10
    max_limit = 50

    def get_paginated_data(self, data):
        return OrderedDict([
            ('limit', self.limit),
            ('offset', self.offset),
            ('count', self.count),
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),
            ('results', data)
        ])

    def get_paginated_response(self, data):
        """
        我们重新定义此方法以返回 `limit` 和 `offset`。
        这被前端用于自己构建分页。
        """
        return Response(OrderedDict([
            ('limit', self.limit),
            ('offset', self.offset),
            ('count', self.count),
            ('next', self.get_next_link()),
            ('previous', self.get_previous_link()),