简体   繁体   中英

How to AND chain filters in a django queryset?

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.

Try this:

from django.db.models import Q

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM