当模型不相关时,如何使用 Django ORM 执行 SQL JOIN?

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

我有两个看起来像这样的模型:

(表A)

class ModelA(models.Model):
    student_id = models.TextField()
    name = models.TextField()
    age = models.IntegerField()

(表B)

class ModelB(models.Model):
    student_id = models.TextField()
    report_card_file_id = models.TextField()
    # Other fields in ModelB

我创建了一个 sql 查询来加入它们,如下所示:

SELECT
    tableA.*,
    tableB.report_card_file_id
FROM
    tableA
    LEFT JOIN tableB ON tableA.student_id = tableB.student_id
    where tableB.report_card_file_id is not null;

但是如何将此查询转换为 Django orm,以便我拥有一个包含 Student_id、name、age 和 report_card_file_id 的 QuerySet?

这是我的一些代码,但我不知道如何填写?:

a = ModelA.objects.all()
a = a.annotate(?)

我也尝试过使用 .raw() 但后来我得到了一个 RawQuerySet 而不仅仅是一个 QuerySet。

python django orm left-join
1个回答
0
投票

这有点困难,但你可以这样做,我很久以前就这样做过

result = ModelA.objects.annotate(
    report_card_file_id=F('modelb__report_card_file_id')
).filter(
    Q(modelb__report_card_file_id__isnull=False) | Q(report_card_file_id__isnull=False)
).distinct()
© www.soinside.com 2019 - 2024. All rights reserved.