【问题标题】:Django: Paginate by sorted SerializerMethodFieldDjango:按排序的 SerializerMethodField 分页
【发布时间】:2014-12-31 23:01:36
【问题描述】:

我在对按rest_frameworkSerializerMethodField 排序的json 数据进行分页时遇到问题。在开始向列表视图添加分页之前,我将排序后的 json 数据放在上下文变量中,如下所示:

class ExampleList(ListView):
    ...
    def get_context_data(self, **kwargs):
        context = super(ExampleList, self).get_context_data(**kwargs)
        context["examples"] = sorted(ExampleSerializer(
            submissions, many=True, context={'request': self.request}
        ).data, key=lambda x: x.get("score"), reverse=True)
        return context
    ...

这很有效,因为 lambda 函数抓取了分数,并按它排序,这正是 sorted() 应该如何工作的。问题始于分页。我已经研究了几天,没有任何方法可以通过我可以找到的json数据进行分页。仅通过查询集。

当我开始分页时,这是我的两个序列化程序类:

class ExampleSerializer(serializers.ModelSerializer):
    score = serializers.SerializerMethodField('get_score')

    class Meta:
        model = Example
        fields = ('id', '...', 'score',)

    def get_score(self, obj):
        return obj.calculate_score()

class PaginatedExampleSerializer(pagination.PaginationSerializer):
    class Meta:
        object_serializer_class = ExampleSerializer

在我的一个列表视图中,我创建了一个排序的上下文对象,它按score 对序列化数据进行排序并对其进行分页。我还创建了一个调用分页的方法,称为paginate_examples()。如您所见,它首先按查询集分页,然后在每个分页页面上按score 对数据进行排序。所以应该在第 1 页上的东西一直在第 5 页左右。

class ExampleList(ListView):
    queryset = Example.objects.all()

    def paginate_examples(self, queryset, paginate_by):
        paginator = Paginator(queryset, paginate_by)
        page = self.request.GET.get('page')
        try:
            examples = paginator.page(page)
        except PageNotAnInteger:
            examples = paginator.page(1)
        except EmptyPage:
            examples = paginator.page(paginator.num_pages)

        return PaginatedExampleSerializer(examples, context={'request': self.request}).data

    def get_context_data(self, **kwargs):
        context = super(ExampleList, self).get_context_data(**kwargs)

        pagination = self.paginate_examples(self.queryset, self.paginate_by)
        examples = pagination.get("results")
        context["examples"] = sorted(examples, key=lambda x: x.get("score"), reverse=True)
        context["pagination"] = pagination
        return context

同样,问题在于应该在/?page=1 上显示的列表项正在/?page=x 上显示,因为PaginatedExampleSerializer 在数据被SerializerMethodField 排序之前对数据进行了分页。

有没有办法对已经序列化的数据进行分页,而不是在 Django 中通过queryset 进行分页?还是我必须自己创建一些方法?我想避免将score 设为数据库字段,但如果我无法找到解决方案,那么我想我将不得不这样做。 对此的任何帮助将不胜感激。

【问题讨论】:

    标签: django pagination django-rest-framework


    【解决方案1】:

    有点晚的答案,但可能会帮助发现自己在这里的人。

    我有一个类似的问题,我需要在输出中组合两个单独的模型,选择两个模型中的最后一项,并进行分页和排序。我发现 OrdereringFilter 对我的要求来说有点太多了,所以选择默认排序,但这也适用于 OrderingFilter

    基本的做法是通过database functionsaggregate functionannotate序列化器计算出的字段来确定路径。

    from rest_framework.pagination import LimitOffsetPagination
    from rest_framework.generics import ListAPIView
    from django.db.models import Q, Count, Avg
    from django.db.models.functions import Greatest
    
    class ExampleListViewPagination(LimitOffsetPagination):
        default_limit = 10
    
    class ExampleSerializer(serializers.ModelSerializer):
        
        def get_last_message_and_score(self, obj):
            # added to obj via the view get_queryset annotate
            return {
              "last_message": self.get_last_comment_or_file(),
              "last_message_time": obj.last_message_time,
              "score": obj.score
             }
    
        class Meta:
            model = Example
            fields = ('id', '...', 'last_message_and_score',)
    
    class ExampleList(ListAPIView):
        serializer_class = ExampleSerializer
        pagination_class = ExampleListViewPagination
    
        def get_queryset(self):
            # the annotation here is being used for the pagination to work
            # on last_message_time, and hypothetical calculate_score
            # both descending
            qs = (
                Example.objects.filter(
                    Q(item__parent__users=self.get_user())
                    & (
                        Q(last_read_by_user=None)
                        | Q(last_read_by_user__lte=timezone.now())
                    )
                )
                .exclude(
                    Q(user_comments__isnull=True) 
                    & Q(user_files__user_item_files__isnull=True)
                )
                .annotate(
                    last_message_time=Greatest(
                        "user_comments__created",
                        "user_files__user_item_files__created",
                    ),
                    score=Avg(Count("user_comments"), Count("user_files__user_item_files")),
                    )
                )
                .distinct()
                .order_by("-last_message_time", "-score")
            )
            return qs
    
    

    这里需要注意的一点是 prefetch_related 和 select_related 可能能够稍微优化查询。

    我尝试探索的其他选项之一是基于覆盖rest_framework.pagination.LimitOffsetPagination 上的paginate_queryset 以在数据库查询和查询集之外进行分页,但发现注释更容易。

    【讨论】:

      猜你喜欢
      • 2015-07-14
      • 1970-01-01
      • 2020-10-20
      • 2016-12-27
      • 2014-12-10
      • 2016-07-21
      • 2020-12-09
      • 1970-01-01
      • 2018-12-12
      相关资源
      最近更新 更多