【问题标题】:Use additional request param to generate a model field in DRF 3使用附加请求参数在 DRF 3 中生成模型字段
【发布时间】:2017-01-12 11:16:08
【问题描述】:

我是 Djnago Rest Framework 3 的新手,无法理解如何实现这一点:
我有以下型号:

class Interface(models.Model):  
    name = models.CharField(max_length=25)
    current_location = models.CharField(max_length=25, blank=True)

在请求参数中,我期望纬度、经度字段将从纬度、经度生成 geohash 并存储在 current_location 中。

我尝试使用以下序列化程序和 ViewSet,但它给出了错误

“接口”对象没有“纬度”属性。

class InterfaceSerializer(serializers.ModelSerializer):
    latitude = serializers.FloatField()
    longitude = serializers.FloatField()
    class Meta:
        model = Interface
        fields = ('id', 'name', 'latitude', 'longitude',)
        read_only_fields = ('id',)

class InterfaceViewSet(viewsets.ModelViewSet):
"""                                                                                                                                              
API endpoint that allows interface to be viewed or edited.                                                                                       
"""
    queryset = Interface.objects.all()
    serializer_class = InterfaceSerializer

即使使用 serializers.Serializer 而不是 serializers.ModelSerializer 也会出现同样的错误。
这里有什么问题?
如何为给定的模型和需求构建序列化器?

【问题讨论】:

    标签: django django-rest-framework


    【解决方案1】:

    您认为序列化程序如何知道latitutelongitute 字段的用途?
    您应该覆盖 create 方法并手动设置 current_location

    class InterfaceSerializer(serializers.ModelSerializer):
        latitude = serializers.FloatField()
        longitude = serializers.FloatField()
    
        class Meta:
            model = Interface
            fields = ('id', 'name', 'latitude', 'longitude',)
    
        def create(self, validated_data):
            latitute = validated_data.get('latitude')
            longitude = validated_data.get('longitude')
            name = validated_data.get('name')
            # suppose you want to store it charfield comma separated
            current_location = str(latitute) + ',' + str(longtitute)
            return Interface.objects.create(
                             current_location=current_location,
                             name=name
                             )
    

    还有一个有用的包django-geoposition它提供了用于地理定位的字段和小部件。

    【讨论】:

    • 我在 create 方法中尝试过这个,但它给出了同样的错误,即“接口”对象没有属性“纬度”。在可浏览的 API 中。
    • @r.bhardwaj 你写的和我一样吗?也许你在你的代码Interface.objects.create(**validated_data) 中写了这样的东西,所以你得到一个错误。你试过我的代码吗?它应该工作
    • 是的,我已经尝试过你的代码,但它给出了同样的错误,因为我已经调试了代码。错误出现在创建方法之前。以下是错误的详细信息: AttributeError: Got AttributeError when trying to get a value for field latitude on serializer InterfaceSerializer。序列化程序字段可能命名不正确,并且与接口实例上的任何属性或键都不匹配。原始异常文本是:“接口”对象没有属性“纬度”。仅供参考,已将此序列化程序应用于具有 queryset = Interface.objects.all() 的视图集
    • @r.bhardwaj 显示你的ViewSet 请也许有一些错误。我认为有一些代码在查询集中传递了错误的键
    • @r.bhardwaj 看起来不错
    猜你喜欢
    • 2015-08-16
    • 2019-07-27
    • 1970-01-01
    • 2021-12-18
    • 1970-01-01
    • 1970-01-01
    • 2020-01-14
    • 2016-09-19
    • 2021-04-26
    相关资源
    最近更新 更多