2

This question makes clear how chaining and multiple argument filters are different but it doesn't specify how to make them chained filters equivalent.

For example, given the code:

query = mymodel.filter(name="Foo",foreignkey_property1="Bar",foreignkey_property2="Zap")

Is it possible to get an and version of this from a chained queryset and have the query above and the query below be equivalent:

query = mymodel.filter(name="Foo",foreignkey_property1="Bar")
query = query.filter(foreignkey_property2="Zap",???)

I'm certain I've read how this is possible, but can't find it.

Community
  • 1
  • 1
  • Ah! Well, thats what my code is doing. How can I make them equivalent? –  Dec 15 '15 at 05:42
  • Is it possible for you to create separate [`Q`](https://docs.djangoproject.com/en/1.9/topics/db/queries/#complex-lookups-with-q-objects) queries for `foreignkey_property1="Bar"` and `foreignkey_property2="Zap"` conditions and then combine them in a single `filter`? – awesoon Dec 15 '15 at 06:05
  • Hmmm... I've rewritten this using Q()'s but I'd like to leave this open to see if there are other solutions in case someone doesnt have that luxury. –  Dec 16 '15 at 08:22

1 Answers1

2

Try this:

from django.db.models import Q

query = mymodel.filter(Q(name="Foo",foreignkey_property1="Bar") && Q(foreignkey_property2="Zap"))
Dean Christian Armada
  • 6,724
  • 9
  • 67
  • 116