gpt4 book ai didi

Django 自定义左外连接

转载 作者:行者123 更新时间:2023-12-03 10:41:50 25 4
gpt4 key购买 nike

我已经用这个查询了 Django 模型

news = News.objects.filter(Q(likes__user__isnull=True)|Q(likes__user=user))
.extra(select={"is_liked":NewsLikes._meta.db_table+".user_id = %d" % user.id})

这给了我以下查询
SELECT (shows_newslikes.user_id = 143) AS `is_liked`, * FROM `shows_news` 
LEFT OUTER JOIN `shows_newslikes` ON ( `shows_news`.`id` = `shows_newslikes`.`news_id`)
WHERE (`shows_newslikes`.`user_id` IS NULL OR `shows_newslikes`.`user_id` = 143 )

我想要的是以下查询作为结果
SELECT (shows_newslikes.user_id = 143) AS `is_liked`, * 
FROM `shows_news` LEFT OUTER JOIN `shows_newslikes` ON ( `shows_news`.`id` =
`shows_newslikes`.`news_id` and `shows_newslikes`.`user_id` = 143 ) WHERE
(`shows_newslikes`.`user_id` IS NULL )

那么我在查询 Django 模型时必须做什么

最佳答案

很难生成这种形式的 LEFT OUTER JOIN不使用 raw() ;您还需要distinct()重复的行。我会用 EXISTS哪个更干净,可能更快:

news = News.objects.extra(select={'is_liked':
'EXISTS (SELECT 1 FROM {tbl_2} '
'WHERE {tbl_2}.news_id = {tbl}.id AND {tbl_2}.user_id = %s)'.format(
tbl=News._meta.db_table,
tbl_2=NewsLikes._meta.dbtable)}, select_params=(user.id,))

关于Django 自定义左外连接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25820170/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com