Django restframework - 如何按优先级顺序将两个queryset组合到Serialize?

时间:2015-01-20 06:44:59

标签: python django django-rest-framework django-queryset django-serializer

这是我原来的疑问:              Movie.objects.filter(releaseday__gte=past_month.date(),releaseday__lte=today.date(),movie__movietime__gte=today).extra({'vrank': 'CASE WHEN hotrank=0 THEN 4 WHEN hotrank >=4 THEN 4 ELSE hotrank END'}).distinct().order_by('vrank','-releaseday')

但结果有重复 我查看了该文档,它说问题是order_by()distinct()一起使用

所以现在我需要按顺序组合queryset1queryset2。 首先显示queryset1的结果,
然后queryset2 请帮帮我谢谢

views.py:

class MovieList(MovieMixin, generics.ListAPIView):
    serializer_class = MovieSerializer

    def get(self, request, *args, **kwargs):
        if request.GET.get("top"):
            self.top(top)
        return super(MovieList, self).get(request, *args, **kwargs)

    def top(self,top):    
        queryset1 = Movie.objects.filter(releaseday__gte=past_month.date(),releaseday__lte=today.date(),movie__movietime__gte=today,hotrank__lte=3).exclude(hotrank=0).distinct().order_by('hotrank')
        queryset2 = Movie.objects.filter(releaseday__gte=past_month.date(),releaseday__lte=today.date(),movie__movietime__gte=today).exclude(hotrank__lte=3,hotrank__gte=1).distinct().order_by('-releaseday')

        self.queryset =( queryset1 | queryset2 )

1 个答案:

答案 0 :(得分:0)

您可以尝试使用此

from itertools import chain
....
self.queryset = sorted(chain(queryset1, queryset2),
    key=lambda instance: instance.releaseday)

这将组合queryset 1和queryset 2,然后按值realaseday对它们进行排序。