Django从具有FK的相关模型中获取数据



如何创建此查询集:

SELECT 
p.*,
o.name,
o.link
FROM property p
INNER JOIN listing l on l.property_id = p.id
INNER JOIN ota o on o.id = l.ota_id

型号

class Property(Model):
code = CharField()
...
class Listing(Model):
ota = ForeignKey(Ota)
property = ForeignKey(Property)
class Ota(Model):
name = Charfield()
link = Charfield()

使用Property.objects.all(),我可以在返回的对象中看到有一个listing_set

比方说:

queryset = Property.objects.all()
queryset[0].listing_set.all()

但它带来了整个模型,而不是与property_id相关的;

还试图用SerializerMethodField在序列化程序中获取Ota数据,并执行新的查询来获取这些信息,但性能显著下降。

我认为您应该使用related_name

相关名称

class Property(Model):
code = CharField()
...
class Listing(Model):
ota = ForeignKey(Ota)
property = ForeignKey(Property,related_name='listinings')
class Ota(Model):
name = Charfield()
link = Charfield()

pp=Property.objects.first()
pp.listinings.all()

最新更新