【问题标题】:Set page of ViewSet in Django REST Framework在 Django REST Framework 中设置 ViewSet 的页面
【发布时间】:2013-11-13 16:36:49
【问题描述】:

我有以下代码:

class GeonamesCountryViewSet(viewsets.ReadOnlyModelViewSet):
    permission_classes = (AllowAny,)
    serializer_class = GeonamesCountrySerializer
    ordering = ('country_name',)
    offset_limit = 'required'

    def get_queryset(self):
        country_geoname_ids = self.request.QUERY_PARAMS.get('country_geoname_ids', None)
        name_prefix = self.request.QUERY_PARAMS.get('name_prefix', None)

        if (country_geoname_ids is None) and (name_prefix is None):
            raise exceptions.ParseError("Either 'country_geoname_id' or 'name_prefix' must be defined.")

        if country_geoname_ids is not None:
            country_geoname_ids = [param.strip() for param in country_geoname_id.split(',')]
            queryset = GeonamesCountry.objects.filter(country_geoname_id__in = country_geoname_ids)

        if name_prefix is not None:
            if len(name_prefix) < 2:
                raise exceptions.ParseError("'name_prefix' must be at least 2 characters long")
            queryset = GeonamesCountry.objects.filter(country_name__istartswith = name_prefix)

        paginator = Paginator(queryset, self.request.QUERY_PARAMS.get('limit', 10))
        selected_page = self.request.QUERY_PARAMS.get('page')

        try:
            countries = paginator.page(selected_page)
        except EmptyPage:
            raise exceptions.ParseError("'Page Empty")


        return queryset

抛出 EmptyPage 异常时是否可以默认为第一页而不是 raise exceptions.ParseError("'Page Empty")?

阅读文档后,我发现不使用 ViewSet 时很容易完成,但如何在 ViewSet 中完成?

【问题讨论】:

    标签: python django django-views django-rest-framework


    【解决方案1】:

    我认为你这样做会很安全:

    try:
        countries = paginator.page(selected_page)
    except InvalidPage:
        countries = paginator.page(1)
    

    注意InvalidPage 异常,因此您也可以覆盖非数字。

    -- 更新--

    似乎最干净的方法是覆盖分页类,这是让您控制返回页码的唯一方法:

    from django.core.paginator import Paginator, InvalidPage
    
    class MyPaginator(Paginator):
        def validate_number(self, number):
            try:
                number = super(MyPaginator, self).validate_number(number)
            except InvalidPage:
                number = 1
    
            return number
    
    
    class GeonamesCountryViewSet(viewsets.ReadOnlyModelViewSet):
        paginator_class = MyPaginator
        ...
    

    【讨论】:

    • 感谢您的回答。是的,实际上我知道这一点,但是我的问题是如何在 ViewSet 的输出上设置分页器? ViewSet 自己负责页面分页,因此即使我使用您上面放置的代码,它也不会将页面设置为第 1 页。
    猜你喜欢
    • 2020-07-22
    • 2015-10-25
    • 2014-07-01
    • 2014-05-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-01
    • 1970-01-01
    相关资源
    最近更新 更多