如何在django休息框架中分页过滤器 [英] How to paginate with filters in django rest framework

查看:94
本文介绍了如何在django休息框架中分页过滤器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前有一个API视图设置如下:

I currently have an API view setup as follows:

class WeatherObservationSerializer(serializers.ModelSerializer):
    dew_point = serializers.Field(source='dew_point')
    wind_gust = serializers.Field(source='get_wind_gust')

    class Meta:
        model = WeatherObservation
        fields = ('id', 'station', 'temperature', 'pressure', 'humidity',
                  'wind_direction', 'wind_speed', 'rainfall', 'date',
                  'dew_point', 'wind_gust')

class WeatherObservationList(generics.ListCreateAPIView):
    model = WeatherObservation
    serializer_class = WeatherObservationSerializer
    permission_classes = (permissions.IsAuthenticatedOrReadOnly,)

    def get_queryset(self):
        queryset = WeatherObservation.objects.all()
        min_date = self.request.QUERY_PARAMS.get('min_date', None)
        station = self.request.QUERY_PARAMS.get('station', None)
        if min_date is not None:
            queryset = queryset.filter(date__gte=min_date)
        if station is not None:
            queryset = queryset.filter(station=station)
        return queryset

我的 settings.py 包含:
REST_FRAMEWORK = {
'PAGINATE_BY':50,
'PAGINATE_BY_PARAM':'page'
}

My settings.py contains: REST_FRAMEWORK = { 'PAGINATE_BY': 50, 'PAGINATE_BY_PARAM': 'page' }

当我向API发出请求时,如下所示:/ api / weather / observations /?station = 2& page = 2& min_date = 2013-3-14我只得到两个结果。如果是第3页,3个结果等等。是否有任何错误导致了这个问题?

When I make a request to the API like so: /api/weather/observations/?station=2&page=2&min_date=2013-3-14 I only get back two results. If it's for page 3, 3 results, and so on. Is there anything I'm doing wrong that is causing this problem?

干杯。

推荐答案

查看文档设置:


PAGINATE_BY_PARAM

PAGINATE_BY_PARAM

查询参数的名称,可以是由客户端用来覆盖用于分页的默认页面大小。如果设置为None,客户端可能不会覆盖默认页面大小。

The name of a query parameter, which can be used by the client to overide the default page size to use for pagination. If set to None, clients may not override the default page size.

只需从您的settings.py中删除该行,您应该

Simply remove that line from your settings.py and you should be fine.

更新1/7/2016:

UPDATE 1/7/2016:

请注意,此设置目前正在弃用。您可以参考分页指南更多细节。

Note that this setting is now in the process of deprecation. You can consult the pagination guide for more details.

简短版本是您现在应该使用适合您的视图的适当设置创建自定义分页类。链接指南中的示例应该更有用。

The short version is that you should now create a custom Pagination class with the appropriate settings which you then apply to your view. The examples in linked guide should be more than helpful.

这篇关于如何在django休息框架中分页过滤器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆