python - Django:通过外键将两个表连接到第三个表?

标签 python django

我有三个模型

class A(Model):
    ...

class B(Model):
    id = IntegerField()
    a = ForeignKey(A)

class C(Model):
    id = IntegerField()
    a = ForeignKey(A)

我想要获取 (B.id, C.id) 对,其中 B.a==C.a。如何使用 django orm 进行连接?

最佳答案

Django 允许您 reverse the lookup与使用 __ 进行正向查找的方式大致相同:

It works backwards, too. To refer to a “reverse” relationship, just use the lowercase name of the model.

This example retrieves all Blog objects which have at least one Entry whose headline contains 'Lennon':

Blog.objects.filter(entry__headline__contains='Lennon')

我认为你可以做这样的事情,@Daniel Roseman 对你将返回的结果集类型的警告。

ids = B.objects.prefetch_related('a', 'a__c').values_list('id', 'a__c__id')

如果内存可用,预取相关功能将有助于提高旧版本 django 的性能。

关于python - Django:通过外键将两个表连接到第三个表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58915820/

相关文章:

python - github如何计算项目代码中语言的比例?

python - 图像文件不是 type1

python - Django 中的 Pisa (XHTML -> PDF) 不会显示 PDF 格式的图像

python - 在 Jinja2 中,如何结合 block 标签使用宏?

Django Rest Framework Many=False 产生错误

python - 如何避免 Django 模型中的日期重叠?

python - 解析多行日志文件,其中的上下文更改行

python - 如何读取文件夹中的文件名并按字母顺序和递增顺序访问它们?

python - 如何使用 matplotlib Python 绘制时间序列

django "manage.py index"不作为 cron 作业执行