作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我需要开始说,类似问题中提供的解决方案似乎都不适合我。
我有两个模型
class Building(models.Model):
(...)
address = models.ForeignKey('common.Address', null=True)
class Address (models.Model):
(...)
latlng = models.PointField(null=True)
我正在使用 Django REST Framework(带有附加 GIS 扩展)序列化器来序列化这些模型:
class BuildingSerializer(serializers.ModelSerializer):
class Meta:
model = Building
class AddressSerializer(serializers.GeoModelSerializer):
class Meta:
model = Address
使用默认序列化器,我得到的 JSON 如下所示:
results": [
{
(...)
"address": 1
}
]
所需的 JSON 如下所示:
results": [
{
(...)
"address": 1,
"latlng": {
"type": "Point",
"coordinates": [
11.0,
11.0
]
},
},
]
其中 latlng 是地址字段,哪个建筑物只能有一个。
使用这个http://www.django-rest-framework.org/api-guide/serializers/#dealing-with-nested-objects抛出和错误:
Got AttributeError when attempting to get a value for field `latlng` on serializer `BuildingSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `Building` instance.
Original exception text was: 'Building' object has no attribute 'latlng'.
最佳答案
最简单的方法是将 latlng 字段添加到 Building 序列化程序并实现一个方法来检索它:
class BuildingSerializer(serializers.ModelSerializer):
class Meta:
model = Building
latlng = serializers.SerializerMethodField()
def get_latlng(self, obj):
if obj.address and obj.address.latlng:
return {
"type": obj.address.latlng.geom_type,
# any other fields in latlng
}
关于python - 如何在 Django REST Framework 中正确嵌套序列化器?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28558401/
我是一名优秀的程序员,十分优秀!