1

I have a rather strange problem in Django, where I do not see how I could combine "__contains" and "__in" in a single statement.

So, here is my situation: I have a list of entries like so:

a = ["hgfjhgj89789jkbjk", "jhgjkhj89789jkhkjh", "jhgkjhkj89689gfghdfhg"]

and I would like to check this list against a queryset - which I would normally do like so:

queryset = MyModel.objects.all().filter(my_field__in=a)

However, in my situation, my_field does not exactly match the values in a and therefore, I am having to resort to __contains like so:

queryset = MyModel.objects.all().filter(my_field__contains=a[0])

..but then, my a has now 2000 entries, and I cannot run the above query 2000times - sounds silly.

So, how can I combine this "__contains" with "__in"? Sorry if this is a daft question!

AJW
  • 5,569
  • 10
  • 44
  • 57

1 Answers1

5

This can't be done with one filter, but it could be done using Django's Q objects:

from django.db.models import Q

query = Q()
for entry in a:
    query = query | Q(my_field__contains=entry)

queryset = MyModel.objects.filter(query)

Q objects let you do complex queries in one go - check out the docs for more examples.

Ben
  • 6,687
  • 2
  • 33
  • 46
  • Does this preserve the order of the values in `a`? – AJW May 24 '15 at 19:45
  • I'm not sure what you mean. The resulting queryset will be ordered by whatever ordering the database spits out. – Ben May 24 '15 at 19:50
  • The problem seems to be that `a`'s order is not preserved in the resulting queryset - if you know what I mean.. so if `a=[1,2,3]` the queryset spits out the results in a different order...Is there any way to preserve this order of `a` in the resulting queryset? – AJW May 24 '15 at 19:55
  • At the database level, you can only order by fields. So you could order the result by my_field - but you can't make all the ones that matched a[0] come first, then those that matched a[1], etc. You'd have to do that in Python afterwards. – Ben May 24 '15 at 19:57
  • ok Ben - understood :) Accepted your answer! Thanks a tonne! – AJW May 24 '15 at 19:58