我有三个模型
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/