David542
David542

Reputation: 110562

Using booleans on objects.filter() in Django

How would I use booleans on an objects filter. For example --

Emails.objects.filter(id=1 or id=2)

Emails.objects.filter(name='tom' and domain = 'gmail.com')

How would these translate into useable syntax? Thank you.

Upvotes: 1

Views: 155

Answers (2)

phunehehe
phunehehe

Reputation: 8778

Another way to do OR is to use Q. You can AND and OR them just like booleans

# Filter emails whose id is 1 or 2
Emails.objects.filter(Q(id=1) | Q(id=2))

Of course the intended use of Q is so that you can construct queries like

# Filter emails whose id is 1 or name is 'tom'
Emails.objects.filter(Q(id=1) | Q(name='tom'))

To do AND the obvious way is to specify one attribute after another like in Ignacio's answer :)

Upvotes: 5

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799490

Emails.objects.filter(id__in=[1, 2])

Emails.objects.filter(name='tom', domain='gmail.com')

Upvotes: 4

Related Questions