如何在 Django 过滤器中使用 AND?

如何创建一个“ AND”过滤器来检索 Django 中的对象?我想要检索一个在单个字段中有两个单词组合的行。

例如,当我在 mysql 数据库上运行下面的 SQL 查询时,它正是这样做的:

select * from myapp_question
where ((question like '%software%') and (question like '%java%'))

如何使用过滤器在 Django 中实现这一点?

94240 次浏览

(update: this answer will not work anymore and give the syntax error keyword argument repeated)

mymodel.objects.filter(first_name__icontains="Foo", first_name__icontains="Bar")

update: Long time since I wrote this answer and done some django, but I am sure to this days the best approach is to use the Q object method like David Berger shows here: How do I use AND in a Django filter?

You can chain filter expressions in Django:

q = Question.objects.filter(question__contains='software').filter(question__contains='java')

You can find more info in the Django docs at "Chaining Filters".

For thoroughness sake, let's just mention the Q object method:

from django.db.models import Q
criterion1 = Q(question__contains="software")
criterion2 = Q(question__contains="java")
q = Question.objects.filter(criterion1 & criterion2)

Note the other answers here are simpler and better adapted for your use case, but if anyone with a similar but slightly more complex problem (such as needing "not" or "or") sees this, it's good to have the reference right here.