如何创建此查询集:
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()