Django rest框架:嵌套对象未传递给validated_data [英] Django rest framework: Nested object not passing to validated_data

查看:327
本文介绍了Django rest框架:嵌套对象未传递给validated_data的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在理解序列化器的工作方式时,这肯定是一个问题。

This is surely a problem in my understanding of how the serializer should work.

在更改序列化器的属性权限后,我发现我的Author嵌套对象

After changing a property permissions on my serializer, I found out that my Author nested object is turning out empty on the validated_data.

这是我的代码:

class ThreadSerializer(serializers.Serializer):
    class Meta:
            model = Thread
            queryset=Thread.objects.all()
            fields = ('id', 'title', 'description', 'author', 'created_at')

    pk = serializers.IntegerField(read_only=True)
    title = serializers.CharField(required=False, allow_blank=False, max_length=100)
    description = serializers.CharField(style={'base_template': 'textarea.html'}, required=False)
    author = AuthorSerializer()
    created_at = serializers.DateTimeField(required=False)

    def create(self, validated_data):
        """
        Create and return a new `Thread` instance, given the validated data.
        """
        author_data = validated_data.pop('author')
        if author_data:
            author = Author.objects.get_or_create(**author_data)
            validated_data['author'] = author

        return Thread.objects.create(**validated_data)

有效负载也很简单:
{ title: 2, description: testing nested objects, author:{ name: ron, email: email@mail.com}}

但是,关于validated_data变量,我所看到的只是一个空

Yet, on the validated_data variable all I see is an empty OrderedDict.

有人可以指出我应该在哪里解决这个问题?

Can someone point me to where I should be fixing this?

推荐答案

这里的问题在客户端。

信息是作为表单数据而不是作为ajax请求的application / json传递的。

Information was being passed as form-data and not as application/json on the ajax request.

这篇关于Django rest框架:嵌套对象未传递给validated_data的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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