5

I wanted to do a query based on a list. I know I can do this:

lists = [Everton, Liverpool, Villa]
queryset = Betting.objects.filter(matches__in=list)

However, this doesnt query the table in order. The operation am doing is based on fuzzywuzzy and is vital the query is done in order of the list

I have seen this solution django-create-a-queryset-from-a-list-preserving-order.html but it doesnt seem to work with sqllite

Thanks..Any help will be appreciated

Jaroslav Kadlec
  • 2,505
  • 4
  • 32
  • 43
Lawrence Muriuki
  • 136
  • 1
  • 10

2 Answers2

3

Try something like this:

from django.db.models import Case, Value, When, IntegerField

cases = [When(matches=x, then=Value(i)) for i,x in enumerate(lists)] 
case = Case(*cases, output_field=IntegerField())
queryset = Betting.objects.filter(matches__in=lists)
queryset = queryset.annotate(my_order=case).order_by('my_order')
wim
  • 338,267
  • 99
  • 616
  • 750
0

Not really sure of efficiency, but it can be a way

lists = [Everton, Liverpool, Villa]
queryset = Betting.objects.all()
for i in lists:
    queryset = queryset.filter(matches=i)

The reason you can do is that if you do, queryset.filter(some condition).filter(some other condition), then the result is actually the union of both filters in their order

Shubham Aggarwal
  • 353
  • 2
  • 16