Django Custom Left Outer Join

时间:2014-09-13 05:38:27

标签: django

我用这个

查询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模型时需要做什么

1 个答案:

答案 0 :(得分:3)

如果不使用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,))