什么是Django中的Serializers to_internal_value方法 [英] What is Serializers to_internal_value method used for in Django

查看:103
本文介绍了什么是Django中的Serializers to_internal_value方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些带有ForeignKey的模型和带有relatedField的序列化器.但我有一个错误,说to_internal_value首先需要实现.但是,我不知道该方法的使用,并且无法在网络上找到任何有用的参考.对此的任何帮助均胜过赞赏.

I have some models with foreignKey and serializers with a relatedField. But I have an error saying that to_internal_value needs to be implemented first. However, I don't know the use of this method and could not find any useful reference on the web. Any help explaining this is more than appreciated.

推荐答案

要更新序列化程序的外部字段,我们使用 serializer.relatedField 具有两个功能: to_representation to_internal_value . to_representation 用于修改API的GET正文, to_internal_value 用于验证序列化程序的更新请求,例如,它将帮助您检查请求是否正确另一个表中是否存在用于更新relatedField的东西,诸如此类.

To update the foreign fields for a serializer we use serializer.relatedField which have two functions: to_representation and to_internal_value. to_representation is used to modify the GET body for your API and to_internal_value is used to validate the update request for your serializer, for example, it will help you in checking if the request for updating relatedField is present in the other table or not and things like that.

假设我们有2个模型.一个是 Foo ,另一个是 Bar ,而 Foo Bar 的外键,因此我们需要编写以下序列化程序以这种方式验证和更新外键.

Let's say we have 2 models. One is Foo and the other is Bar, and Foo is Foreign Key to Bar, so we need to write the following serializer to validate and update foreign keys that way.

这是代码段:-

class FooField(serializers.RelatedField):

    def to_representation(self, obj):
        return {
            'id': obj.id,
            'name': obj.name,
        }

    def to_internal_value(self, data):
        try:
            try:
                obj_id = data['id']
                return Obj.objects.get(id=obj_id)
            except KeyError:
                raise serializers.ValidationError(
                    'id is a required field.'
                )
            except ValueError:
                raise serializers.ValidationError(
                    'id must be an integer.'
                )
        except Obj.DoesNotExist:
            raise serializers.ValidationError(
            'Obj does not exist.'
            )

class BarSerializer(ModelSerializer):
    foo = FooField(
        queryset=Foo.objects.all()
    )
    class Meta:
        model = Bar

希望这会对您有所帮助.

Hope this will help you.

这篇关于什么是Django中的Serializers to_internal_value方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆