【发布时间】:2016-04-14 20:45:35
【问题描述】:
我有三个模型:Address、Address_localisation(其中 address_id 是 ForeignKey)和 Address_users(其中 address_id 又是 ForeignKey)。
在第一步中,我想通过本地化获取所有地址。 我尝试使用:
data = address.objects.select_related().all().annotate(
longitude=F('address_localisation__longitude'),
latitude=F('address_localisation__latitude')
)
但如果在 address_users 中我有两个(或更多)用户用于一个地址,这会给我两个(或更多)行具有相同地址(因为加入模型)。
所以我只想获取地址和连接的本地化。 我试过的:
data = address.objects.prefetch_related('address_localisation_set').all()
for e in data.all():
for ee in e.address_localisation_set.all():
e.longitude = ee.longitude
e.latitude = ee.latitude
data = list(data.values('id',
'longitude',
'latitude'
))
data = json.dumps(data)
data = json.loads(data)
return JsonResponse(data, safe = False)
但这会导致我出错: “无法将关键字'经度'解析为字段。选择是:id..(地址模型中列出的文件)”
据我了解,这是因为在主模型中我没有经度/纬度字段......但是我应该如何添加它们?
我知道我可以遍历模板中的 address_localisation_set(我没有尝试过,但在 stackoverflow 上找到了解决方案),但是在我的源代码的另一个地方添加字段可能很有用,所以我想知道怎么做.
提前感谢您的宝贵时间
【问题讨论】:
标签: python django views models foreign-key-relationship