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
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,))