【问题标题】:How do I properly nest serializers in Django REST Framework?如何在 Django REST Framework 中正确嵌套序列化程序?
【发布时间】:2015-04-17 23:10:53
【问题描述】:

我需要开始说类似问题中提供的解决方案似乎都不适合我。

我有两个模型

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'.

【问题讨论】:

    标签: python django django-rest-framework geojson django-rest-framework-gis


    【解决方案1】:

    最简单的方法是向 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
                }
    

    【讨论】:

    • 谢谢,很好用!虽然,我还有一个问题。我在 Address 中使用 rest_framework_gis GeoModelSerializer 将 Point 序列化为 GeoJson。在这种情况下,我需要自己写作为回报。我做错了什么还是 GeoModelSerializer 无法序列化字段?尝试使用 GeoModelSerializer 返回普通 latlng 时,我收到 <Point object at 0x7f09332779a0> is not JSON serializable
    • 尝试使用 GeoFeatureModelSerializer。
    • 它抛出 class Meta has no attribute 'geo_field' 我真的不知道如何解释。
    • 看看github.com/djangonauts/django-rest-framework-gis/blob/master/… -- GeoFeatureModelSerializer 要求您定义一个geo_field 以序列化为“几何”。
    • 再次返回is not JSON serializable 错误。我发现 rest_framework_gis 文档有点混乱......我想我会满足于第一个解决方案。感谢所有提示。
    猜你喜欢
    • 2018-10-26
    • 2018-07-07
    • 1970-01-01
    • 1970-01-01
    • 2016-02-09
    • 2018-07-06
    • 1970-01-01
    • 2014-08-20
    • 2015-03-25
    相关资源
    最近更新 更多