[英]How to put list values in django's rest framework json response
在我的django项目之一中,我以这种方式设置了django-rest-framework ,以便它返回以下类型的json响应:
{
"name": "John",
"last_name": "Smith",
"age": 35,
"dl_url": "[u'http://domain.com/file1', u'http://domain.com/file2']"
}
到现在为止还挺好。
问题是我需要将dl_url
属性作为列表而不是字符串返回,以便使其变为:
{
"name": "John",
"last_name": "Smith",
"age": 35,
"dl_url": [u'http://domain.com/file1', u'http://domain.com/file2']
}
最好的方法是什么?
请注意,我将链接存储为我的models.py
的models.TextField(null=True, blank=True)
实例。
先感谢您。
只需使用序列化器方法将其转换为列表即可。 为此,请使用drf 3.0中引入的to_representation方法(在以前的版本中,它被称为transform或smth like)。
def to_representation(self, instance): ret = super(UserSerializer, self).to_representation(instance) ret['dl_url'] = ret['dl_url'].split(',') return ret
尝试这个 :
old_response = { “名”: “约翰”, “姓氏”: “史密斯”, “年龄”:35, “dl_url”:“[U ' http://domain.com/file1 ' U” 的http:// domain.com/file2 ']“}
new_response = old_response
new_response ['dl_url'] = new_response ['dl_url'] [1:-1] .split(',')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.