Tâmer Cuba
Tâmer Cuba

Reputation: 2821

Django ORM query with IN + LIKE

Lets suppose the following model:

class Person(models.Model):
    name = models.CharField(null=False)
    ...

I know that I can filter Persons with a name that contains the letter a using Person.objects.filter(name__contains='a'). And I know that I can filter Persons with name is in a list using Person.objects.filter(name__in=['John Doe', 'Mary Jane']).

Its possible ( or, whats the performative way ) to do the two things using just one filter ?

I know that I can do 2 queries (maybe more) and fetch the data. But in my current case, I have a method on my view called get_filters that returns a Q object that will be used in get_queryset method. So I need to implement this inside a Q object and fetching only 1 query. Its possible ?

Upvotes: 0

Views: 513

Answers (1)

AKX
AKX

Reputation: 168966

Exactly as you figured, you can build up a Q() filter object.

Q(name__contains='a') & Q(name__in=['John Doe', 'Mary Jane'])

However, that will only ever match an object Mary Jane since John Doe doesn't contain an a. (The equivalent SQL is name LIKE '%a%' AND name IN ('John Doe', 'Mary Jane').

If you mean "find any object containing any of these substrings", that's possible too:

q = Q()
for substring in ['John', 'Mary', 'Jane']:
  q |= Q(name__contains=substring)

This will be the equivalent of name LIKE '%John%' OR name LIKE '%Mary%' OR name LIKE '%Jane%'.

Upvotes: 2

Related Questions