简体   繁体   English

我如何实现多个分页(drf)

[英]How i can realize multiple pagination(drf)

If I'll send get request like this enter image description here , i need to have multiple pagination (LimitOffset and PageNumber).如果我要发送这样的获取请求,请在此处输入图像描述,我需要有多个分页(LimitOffset 和 PageNumber)。

models.py:模型.py:

from django.db import models


class Products(models.Model):
    title = models.CharField(max_length=255)
    description = models.TextField(blank=True)
    photo = models.ImageField(upload_to="photos/%Y/%m/%d/", null=True)
    hashtag = models.CharField(max_length=255)
    is_hit = models.BooleanField(default=False)
    category = models.ForeignKey('Category', on_delete=models.PROTECT, null=True)

    def __str__(self):
        return self.title


class Category(models.Model):
    name = models.CharField(max_length=255)

    def __str__(self):
        return self.name

views.py:视图.py:

from rest_framework import generics
from rest_framework.pagination import PageNumberPagination

from .models import *
from .serializers import ProductsSerializer


class PaginationProducts(PageNumberPagination):
    page_size = 2
    page_size_query_param = 'page_size'
    max_page_size = 2


class ProductsAPIList(generics.ListCreateAPIView):
    queryset = Products.objects.all()
    serializer_class = ProductsSerializer
    pagination_class = PaginationProducts

serializers.py序列化程序.py

from rest_framework import serializers

from .models import *


class ProductsSerializer(serializers.ModelSerializer):

    class Meta:
        model = Products
        fields = "__all__"

    def get_photo_url(self, obj):
        request = self.context.get('request')
        photo_url = obj.fingerprint.url
        return request.build_absolute_uri(photo_url)

I need something that can help API client choose number of page and quantity of posts on that page.我需要一些可以帮助 API 客户选择页数和该页上的帖子数量的东西。 Think that in this case i need NumberPagePagination and LimitOffsetPagination.认为在这种情况下我需要 NumberPagePagination 和 LimitOffsetPagination。

I think you don't need to create the custom pagination class.我认为您不需要创建自定义分页 class。

from rest_framework.pagination import LimitOffsetPagination

class ProductsAPIList(generics.ListCreateAPIView):
    queryset = Products.objects.all()
    serializer_class = ProductsSerializer
    pagination_class = LimitOffsetPagination

The offset value corresponds to the page * size in the original pagination and the limit value corresponds to the size . offset值对应于原始分页中的page * sizelimit值对应于size

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM