如何在 Django REST Framework 中正确嵌套序列化程序?

How do I properly nest serializers in Django REST Framework?

我需要开始说 none 类似问题中提供的解决方案似乎对我有用。

我有两个模型

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是address的字段,哪个楼只能有一个。

使用此 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'.

最简单的方法是向 Building 序列化程序添加一个 latlng 字段并实现一个方法来检索它:

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
            }