python - Django REST Framework中ViewSet的设置页面

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

我有以下代码:

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 中完成它?

最佳答案

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

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
    ...

关于python - Django REST Framework中ViewSet的设置页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19959344/

相关文章:

python - Docker 构建似乎看不到 requirements.txt,即使它在同一目录中

ios - 使用 Twitter 在 iPhone 中登录用户并将经过身份验证的用户保存到远程 Django 应用程序

python - django模型字段中字符串参数的含义是什么?

python - 如何修复 Django Rest API 错误?

python - 在使用此多对多关系之前,django "<User: user556>"需要为字段 "id"提供一个值

python - 如何用Python求解非线性三角方程组(MATLAB可以轻松求解)

python - Tensorflow - 使用自定义比较器对张量进行排序

django - 用于过滤 Django 列表的下拉选择选项

python - func (1) 返回的数组与 Python 中的大小不匹配

python - 如何从二维列表中选择一个随机元素