使用混合的filter()和Q对象的Django ORM查询 [英] A Django ORM query using a mix of filter() and Q objects
问题描述
我正在寻找一个稍微复杂的查询,这个查询使用原始SQL很容易编写。以下是原始查询的示例:
I'm looking to create a slightly more complex query that is written fairly easily using raw SQL. Here's an example of the query in raw:
选择我的字段FROM sales WHERE is_paid = False OR status ='toship'AND otherfield = 'FOO'AND anotherfield ='BAR'
SELECT my,fields FROM sales WHERE is_paid = False OR status = 'toship' AND otherfield = 'FOO' AND anotherfield = 'BAR'
这很简单,它会生成所有的结果是is_paid = False,然后是第二个结果设置为我的AND匹配。
This is simple, it generates all the results that are is_paid = False and then a second result set for my AND matches.
现在我知道Q对象,我知道过滤,但我似乎无法围绕如何实现这一点在Django ORM干净地。
Now I know about Q objects, I know about filtering but I can't seem to wrap my mind around how to achieve this in the Django ORM cleanly.
任何提示?
谢谢
推荐答案
您可以继续以有点动态的方式构建Q对象。
You can keep building your Q object in a somewhat dynamic fashion.
示例:
query1 = Q(is_paid=False)
query2 = Q()
if status:
query2 = Q(status=status)
if otherfield:
query2 = query2 & Q(otherfield=otherfield)
if anotherfield:
query2 = query2 & Q(anotherfield=anotherfield)
query = query1 | query2
result = model.objects.filter(query)
这篇关于使用混合的filter()和Q对象的Django ORM查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!