在 Django 中高效左连接多个字段上的两个表

问题描述 投票:0回答:1

我想在这些表上保留外连接。

from django.db import models

class Author(models.Model):
    name = models.CharField(max_length=100)
    email = models.EmailField()

class Book(models.Model):
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.CASCADE)
    publication_date = models.DateField()

我正在寻找的django orm产生的sql查询应该是这样的

select title, author, name as nam from book 
left outer join author on (book.author = author.id AND book.title = author.email)

如何实现这一目标?我尝试使用 FilteredRelation 但我没有正确获取语法,或者使用 django ORM 是否不可能?

django-rest-framework django-orm
1个回答
0
投票

您可以使用 annotate()F() 表达式执行 左外连接

from django.db.models import F

queryset = Book.objects.annotate(
    author_name=F('author__name'),
    author_email=F('author__email')
).values('title', 'author_name', 'author_email')

注意:Django 不直接支持SQL 查询。如果你想查看上面querysetSQL查询

print(str(queryset.query))
© www.soinside.com 2019 - 2024. All rights reserved.