简体   繁体   中英

Django restframework - how to combine two queryset to Serialize in order of priority?

This is my original query: 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')

But the result has duplicate.
I look the document,it said that the proble is use order_by() and distinct() together

So now I need to combine queryset1 and queryset2 in sequence. Show the result of queryset1 first,
then queryset2 Please help me thank you

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 )

You can try using this

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

This will combine queryset1 and queryset2 and then sort them by the value realaseday .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM