简体   繁体   English

Django rest框架如何序列化字符串列表?

[英]Django rest framework how to serialize a list of strings?

I want to give a list of strings in postman, for example: 我想给邮递员提供一个字符串列表,例如:

['string1', 'string2', 'string3', 'string4', 'string5'] ['string1','string2','string3','string4','string5']

But when it reaches serializer.is_valid() it gives me: 但是当它到达serializer.is_valid()时,它给了我:

"non_field_errors": [
            "Invalid data. Expected a dictionary, but got str."
        ]

This is my serializer: 这是我的序列化器:

class URLRequestedSerializer(serializers.Serializer):
    urls = serializers.ListField(child=serializers.CharField())

How can I make the serializer to except a list of strings? 我如何才能使序列化程序除字符串列表之外?

It looks like you posted a list instead of a dictionary as JSON in Postman, just as the error message said. 就像您在错误消息中说的那样,您似乎在Postman中以JSON的形式发布了列表而不是字典。

You posted: 您发布了:

['string1', 'string2', 'string3', 'string4', 'string5']

But you should have posted: 但是您应该已经发布:

{
    "urls": ["string1", "string2", "string3", "string4", "string5"]
}

Remember, your serializer defined the field urls , you therefore have to send the data to the correct field in your JSON body :) 记住,您的序列化程序定义了字段urls ,因此您必须将数据发送到JSON主体中的正确字段:)

从邮递员收到的字符串列表是Django中的字符串类型,请尝试使用eval进行转换。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM