user2302807
user2302807

Reputation: 335

Django filter: pass and array for an OR statement?

I want to query a set with Django with the filter function. The problem is that I want to pass a list of possible values for a given column.

I know I can do the following:

User.objects.filter(Q(username='whatever') | Q(username='whatever2') | (username='whatever3') | ..... )

But the problem is that I have a list of possible usernames.

What I have so far is:

users = []
for username in usernames:
    users.extend(User.objects.filter(username=username))

Is there a more efficient way to do this (make one database query instead of multiples)?

Upvotes: 0

Views: 1154

Answers (1)

adam.lofts
adam.lofts

Reputation: 1162

You can use:

users = User.objects.filter(username__in=usernames)

See https://docs.djangoproject.com/en/dev/ref/models/querysets/#in

Upvotes: 2

Related Questions