0x4B1D
0x4B1D

Reputation: 933

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.

Upvotes: 5

Views: 4078

Answers (2)

SuperNova
SuperNova

Reputation: 27456

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

Samplemodel.objects.filter(field1__in=['x', 'y'])

Upvotes: 3

Konark Modi
Konark Modi

Reputation: 749

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

Upvotes: 12

Related Questions