DRF - 序列化对象中的OrderedDict

时间:2016-04-21 09:24:26

标签: django serialization django-rest-framework

我在使用Django rest框架正确序列化嵌套ModelSerializer方面遇到了问题。嵌套的序列化器成为父JSON对象内的OrderedDict。

我已经使用了Meta.depth值,但它似乎没有任何区别。

单独创建FileTypeSerializer将导致正确形成JSON对象。

有什么建议吗?

串行器:

class FileTypeSerializer(serializers.ModelSerializer):
    class Meta:
        model = FileType

class FileUploadSerializer(serializers.ModelSerializer):
    owner = serializers.SlugRelatedField(
        read_only=True,
        slug_field='id'
    )
    filetype = FileTypeSerializer()

    class Meta:
        model = FileUpload
        read_only_fields = ('created', 'datafile', 'owner', 'filetype')
        depth = 1

工厂:

class FileTypeFactory(factory.DjangoModelFactory):
    class Meta:
        model = FileType

    id = fuzzy.FuzzyInteger(1, 9999)
    name = fuzzy.FuzzyText(length=50)
    description = fuzzy.FuzzyText(length=200)

class FileUploadFactory(factory.DjangoModelFactory):
    class Meta:
        model = FileUpload

    id = fuzzy.FuzzyInteger(1, 9999)
    filetype = factory.SubFactory(FileTypeFactory)
    owner = factory.SubFactory(UserFactory)

测试:

fuf = FileUploadFactory()
serializer = FileUploadSerializer(instance=fuf, context=serializer_context)
import pdb; pdb.set_trace()

结果:

(Pdb) serializer.data
{'owner': 185, 'filetype': OrderedDict([('id', 8855), ('name', u'dFokZyReaOcwCDjAVwxGYhZNVpgOZKeaKRaMWKKHxIDZxceUWr'), ('description', u'ZNOCugfyRaWPGGmfoqZEzoBLknRBVdXyXgYwIFKBJAVuQQKppTiGVMKfgjcjCiUlzmNGFLNQiHIiCEIpydCCtfoWnqrgKOlTZXfUeYLKZgNatsxrRXyWkAEkZmfBjvFFPXcBRshcqIyHMxgHjGjCDBPLJZnEevUXIRAfBnJiLQyHblHONZllglgXhzashLqCvzmNitfN')]), 'datafile': None, 'id': 4960, 'created': '2016-04-21'}

修改

对不起,应该更具体地解决实际问题。问题是来自

的回应
response = self.client.post(url, serializer.data, format='multipart')

说" filetype"是一个必填字段 - 即它没有被正确地解开或其他东西。

encode_multipart

中深入探讨帖子(来自django.test.Client)的代码
(Pdb) lines
['--BoUnDaRyStRiNg', 'Content-Disposition: form-data; name="id"', '', '814', '--BoUnDaRyStRiNg', 'Content-Disposition: form-data; name="owner"', '', '193', '--BoUnDaRyStRiNg', 'Content-Disposition: form-data; name="filetype"', '', 'id', '--BoUnDaRyStRiNg', 'Content-Disposition: form-data; name="filetype"', '', 'name', '--BoUnDaRyStRiNg', 'Content-Disposition: form-data; name="filetype"', '', 'description', '--BoUnDaRyStRiNg', 'Content-Disposition: form-data; name="created"', '', '2016-04-21']
(Pdb) data
{'owner': 193, 'filetype': OrderedDict([('id', 1335), ('name', u'YdmXrMnxeXjzKxYhlLgaGClqTVMbTJIeMvWvQRLWUsVHWQQbFL'), ('description', u'YrmwBkwFhXGqWCNCjUIQdnBHaPQXqAhIXnOaycknMzFZPjWrWtrhYbWYBKdYDJWnRntPNjQranWjbwdBJPnKPLxAbWInfOrGZyGwDaMvlWCVMmylwxzPxCtMRkYJfuetQnvdbcheXQiRWqzFNfrKrWlcpSakmCmxFdsYBjnlxLByfulBBdiGqRdjOvkMxiUWDxasEgdT')]), 'datafile': None, 'id': 814, 'created': '2016-04-21'}

所以看起来文件类型键的值没有被编码。

1 个答案:

答案 0 :(得分:0)

使用此

filetype = FileTypeSerializer(allow_empty_file=True,required=False)