Django Custom Left Outer Join

前端 未结 1 497
野性不改
野性不改 2021-01-13 16:59

I have query the Django model with this

news = News.objects.filter(Q(likes__user__isnull=True)|Q(likes__user=user))
.extra(select={\"is_liked\":NewsLikes._m         


        
相关标签:
1条回答
  • 2021-01-13 17:49

    It's hard to generate this form of LEFT OUTER JOIN without using raw(); Also you need to distinct() duplicated rows. I would use EXISTS which is cleaner and likely to be faster:

    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,))
    
    0 讨论(0)
提交回复
热议问题