Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use filter() to filter same field on two different values in Django ORM?

I have a model (1) that has a field pointing to another model (2). I have a list of values coming from model (2) and I would like to filter objects in model(1) on all of them.

Basically I want to do this:

SomeModel.objects.filter(field1=x OR field1=y OR field1=z)

Is this possible, can't find anything in docs.

like image 639
0x4B1D Avatar asked Jan 13 '12 02:01

0x4B1D


Video Answer


2 Answers

If you want to 'OR' them together, Q objects should help you achieve this:

from django.db.models import Q
Samplemodel.objects.filter(Q(field1='x') | Q(field1='y'))

Ref link: http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

like image 79
Konark Modi Avatar answered Nov 06 '22 19:11

Konark Modi


You can do this using field1__in=['x', 'y']

Samplemodel.objects.filter(field1__in=['x', 'y'])
like image 40
SuperNova Avatar answered Nov 06 '22 21:11

SuperNova