如果我有这3个型号
from django.db import models
class ModelA(models.Model):
name = models.CharField(max_length=50)
class ModelB(models.Model):
tag = models.CharField(max_length=50)
class ModelC(models.Model):
a = models.ForeignKey(ModelA)
b = models.ForeignKey(ModelB)
获取所有ModelA
及其关联ModelB.property
的最佳方法是什么?如果没有原始查询,我无法找到一种好方法。
理想情况下,我可以将其转换为:
[
{
"name": "foo",
"tags": ["tag1", "tag2"]
}
....
]
答案 0 :(得分:1)
在ForeignKeys上使用related_name
from django.db import models
class ModelA(models.Model):
name = models.CharField(max_length=50)
class ModelB(models.Model):
property = models.CharField(max_length=50)
class ModelC(models.Model):
a = models.ForeignKey(ModelA, related_name="theas")
b = models.ForeignKey(ModelB, related_name="thebs")
获取与ModelA实例相关的所有ModelB实例
a_inst = ModelA.objects.get(foo=bar)
ModelB.objects.filter(thebs__a=a_inst)