Django通过和条件退出连接

时间:2019-06-03 12:08:10

标签: django django-models django-queryset

我有3个模型Product,Photo,ProductLikeDislike。我离开了所有三个。为此,我编写了以下查询:

x=Product.objects.values_list('name','photo','productlikedislike')

通过这种方式,我得到了正确的左联接,我打印并像这样检查:

注意olx是我的Django应用的名称。

print(x.query)

SELECT "olx_product"."name", "olx_photo"."id", "olx_productlikedislike"."id"
 FROM "olx_product" LEFT OUTER JOIN "olx_photo" ON ("olx_product"."id" = 
"olx_photo"."reference_id_id") LEFT OUTER JOIN "olx_productlikedislike" ON 
("olx_product"."id" = "olx_productlikedislike"."product_id_id") ORDER BY 
"olx_product"."created" DESC

现在,我想像这样的and语句一起添加额外的ON条件:

ON ("olx_product"."id" = 
    "olx_productlikedislike"."product_id_id"
and "olx_productlikedislike"."product_liked_by_id"=2)

为此,有人建议我使用Django的FilteredRelation。我曾经使用过,但并未与and

一起添加额外的ON条件

我这样使用FilteredRelation

x=Product.objects.annotate( 
productlikedislike_product_liked_by_id=FilteredRelation('productlikedislike',
condition=Q(productlikedislike__product_liked_by_id=2))).values_list('name',
'photo','productlikedislike')

但获得相同的sql查询没有额外的and条件。我正在使用Django 2.1.5

1 个答案:

答案 0 :(得分:0)

通过将'productlikedislike_product_liked_by_id'values_list(...)一起添加到正在使用的FilteredRelation中,我得到了答案。

所以最后一个查询是:

x=Product.objects.filter(Q(photo__cover_photo_flag="yes")|Q(photo__file=None)).annotate( 
productlikedislike_product_liked_by_id=FilteredRelation('productlikedislike',condition=Q(pr
oductlikedislike__product_liked_by_id=2))).values_list('name','photo','productlikedislike_p
roduct_liked_by_id')

我打印了它,这是我想要得到的结果:

SELECT "olx_product"."name", "olx_photo"."id", 
productlikedislike_product_liked_by_id."id" FROM "olx_product" LEFT OUTER JOIN 
"olx_photo" ON ("olx_product"."id" = "olx_photo"."reference_id_id") LEFT OUTER JOIN 
"olx_productlikedislike" productlikedislike_product_liked_by_id ON ("olx_product"."id" =
 productlikedislike_product_liked_by_id."product_id_id" AND 
(productlikedislike_product_liked_by_id."product_liked_by_id_id" = 2)) WHERE
 ("olx_photo"."cover_photo_flag" = yes OR "olx_photo"."file" IS NULL) ORDER BY
 "olx_product"."created" DESC