我正在尝试搜索自引用外键字段上大于和小于值的项目。
在直接SQL中,它很容易(下面的语句是由Django QuerySet生成的,除了我添加的 AND EXISTS 语句):
SELECT *
FROM "model_and_variant"
INNER JOIN "make_and_body_type"
ON ("model_and_variant"."id_make_type" = "make_and_body_type"."id")
LEFT OUTER JOIN "model_and_variant" T3
ON ("model_and_variant"."id_model" = T3."id")
WHERE
"make_and_body_type"."slug" = 'car'
AND EXISTS (
SELECT * FROM "model_and_variant" TX
WHERE TX."id_model" = "model_and_variant"."id"
GROUP BY TX."id"
HAVING MIN(TX."ex_showroom_price") > 200000 AND MAX(TX."ex_showroom_price") <= 500000
)
表“model_and_variant”具有自引用ForeignKey字段“id_model”以映射父(车辆模型)和子(车辆模型变体)
在上面的SQL语句中,我试图搜索变体价格在200000到500000之间的所有模型
在Django中,我很难在语句中添加 AND EXISTS(。如何使用Django ORM QuerySet查找在条件中添加以下内容:
-- ...
AND EXISTS (
SELECT * FROM "model_and_variant" TX
WHERE TX."id_model" = "model_and_variant"."id"
GROUP BY TX."id"
HAVING MIN(TX."ex_showroom_price") > 200000 AND MAX(TX."ex_showroom_price") <= 500000
)
答案 0 :(得分:0)
我使用QuerySet.extra()方法找到了解决方案。
<强>用途:强>
extra_where = """
EXISTS (
SELECT * FROM "model_and_variant" TX
WHERE TX."id_model" = "model_and_variant"."id"
GROUP BY TX."ex_showroom_price"
HAVING MIN(TX."ex_showroom_price") > 200000 AND MAX(TX."ex_showroom_price") <= 500000
)
"""
results = AbcModel.objects.select_related(*select_related).filter(**filters) \
.extra(where=[extra_where])