如何在两个字段上使Django Orm左联接

时间:2019-03-12 08:19:36

标签: python django django-queryset django-orm

我想用Django ORM通过两个字段将两个表连接起来

我有4张桌子

class User:
    ...

class VipUsers:
    library = ForeignKey(Library)
    user = ForeignKey(User)

class Library:
    ...

class Book:
    library = ForeignKey(Library)
    visible = BooleanField(default=None, null=True, blank=True)

在SQL查询中,如下所示:

SELECT b.id, user_id FROM project_book AS b 
LEFT JOIN project_vipusers AS v ON v.library_id=b.library_id AND v.user_id={user_id} 
WHERE CASE 
WHEN b.visible=True THEN v.user_id IS NOT NULL 
WHEN b.visible=False THEN v.user_id IS NULL 
ELSE true 
END;

我尝试做出这样的解决方案,但是django不生成Join查询

my_user = {some_user_id}
Book.objects.all().annotate(
            vip_users=Subquery(VipUsers.objects.filter(library=OuterRef('library'), user=my_user).values('user')[:1]),
            show=Case(When(visible=True, then=Q(vip_users__isnull=False)),
                         When(visible=False, then=Q(vip_users__isnull=True)), 
                         default=Value(True),
                         output_field=BooleanField()
                         )
        ).filter(show=True).distinct().values_list('id', flat=True)

现在有人可以进行这种左联接查询吗?

RawSql和raw()-我无法使用。

0 个答案:

没有答案