Django模型的filter()与extra()
我在使用queryset的extra()方法时遇到了一些问题。
首先,我用下面的方式获取我的对象:
invoices = Invoice.objects.select_related().filter(quantity__gt=0,begin__gte=values['start_day'],end__lte=values['end_day'])
这样做是成功的,我得到了我的发票。
然后我又使用了一次filter():
invoices = invoices.filter(max__gte=duration)
这也成功了。
但是,接下来我需要使用extra()来满足我的请求,所以我得到了:
cond = 'discount="YES" AND priceeuro*(%d%%fixe)<=%d'
invoices = invoices.extra(where=[cond],params=[duration,price])
好吧,这样也能工作,但我的发票变量里包含的元素比之前多了。
感觉就像之前的两个filter()没有起作用一样。
如果你知道原因,
谢谢。
编辑:
这是与查询相关的SQL:
WHERE
("invoice"."product_id" IN (
SELECT U0."id"
FROM "product" U0
WHERE U0."accommodation_id" IN (
SELECT U0."id"
FROM "accommodation" U0
WHERE U0."resort_id" IN (
SELECT U0."id"
FROM "resort" U0
WHERE U0."area_id" IN (
SELECT U0."id"
FROM "area" U0
WHERE U0."country_id" = 9
))))
AND "invoice"."quantity" > 0
AND "invoice"."end" <= 2010-12-31
AND "invoice"."begin" >= 2010-12-01
AND fixe % 7 = 0
AND (discount="YES" AND pricediscountincludedeuro*(7% fixe)<=250)OR(discount="NO" AND priceeuro*(7% fixe)<=250))
1 个回答
1
从查询集对象中导出SQL:
print invoices.query
如果你在查看生成的SQL时,无法明显找到问题的原因,请更新你的提问,并把SQL发给我们看看。
根据看到的SQL的编辑1
我在怀疑你SQL的最后一行(重新格式化后):
...
AND (discount="YES" AND pricediscountincludedeuro*(7% fixe)<=250)
OR (discount="NO" AND priceeuro*(7% fixe)<=250)
)
我觉得你可能想把那两个“折扣”检查放在另一个括号里,这样它们就形成了自己的逻辑检查:
...
AND (
(discount="YES" AND pricediscountincludedeuro*(7% fixe)<=250)
OR
(discount="NO" AND priceeuro*(7% fixe)<=250)
)
)
如果没有这个明确的分组,OR操作会独立于其他“折扣”检查进行比较,这样就会导致包含一些你在上面的条件中已经排除的内容。