Home > Blockchain >  django querySet union?
django querySet union?

Time:10-30

there is situation in which when user search a keyword, the result will be 3 queries

a=model.objects.filter(icontains=keyword[0])
b= a.filter(icontains=keyword)
c= a.filter(istartswith=keyword)

And I want to return a result which combines a, b & c. But the condition is the order should be c,b,a and elements should not be repeated. I tried using union but the order is not correct.

CodePudding user response:

This works and looks a bit cleaner:

records = query1 | query2

If you don't want duplicates, then you will need to append .distinct():

records = (query1 | query2).distinct()

CodePudding user response:

Not sure if I completely understood the question but have to tried:

from django.db.models import Q
queryset = Model.objects.filter(
    Q(icontains=keyword0) & Q(icontains=keyword1) & Q(icontains=keyword2)
)
  • Related