Filter on multiple fields and/or multiple values...

22,060 views
Skip to first unread message

megrez80

unread,
Oct 29, 2008, 9:31:40 PM10/29/08
to Django users
Hello,
I want to do something like the following:

my_query_set = my_table.objects.filter(field1 = some_val and
field2 = another_val)

or
my_query_set = my_model.objects.filter(field1 = some_val or
field1 = another_val)

I couldn't find anything in the docs that describes how to go about
doing this.

Thanks for any help.

Ken....

Ronny Haryanto

unread,
Oct 29, 2008, 10:17:36 PM10/29/08
to django...@googlegroups.com
On Thu, Oct 30, 2008 at 8:31 AM, megrez80 <kda...@gmail.com> wrote:
> I want to do something like the following:
>
> my_query_set = my_table.objects.filter(field1 = some_val and
> field2 = another_val)
>
> or
> my_query_set = my_model.objects.filter(field1 = some_val or
> field1 = another_val)
>
> I couldn't find anything in the docs that describes how to go about
> doing this.

It is in the docs, although it's probably not immediately clear for
people not coming from a python background.

http://docs.djangoproject.com/en/dev/topics/db/queries/#retrieving-specific-objects-with-filters

**kwargs means keyword arguments (note that it's plural). "field1=val"
is one keyword argument. So you can specify more than one and all of
the conditions will be AND-ed together, like so:

Model.objects.filter(field1=val, field2=val)

You can even chain filters together to achieve the same effect:
http://docs.djangoproject.com/en/dev/topics/db/queries/#id1

If you want to OR them together, have a look at Q objects:
http://docs.djangoproject.com/en/dev/topics/db/queries/#complex-lookups-with-q-objects

Ronny

Reply all
Reply to author
Forward
0 new messages