【问题标题】:How to put list values in django's rest framework json response如何将列表值放入 django rest 框架 json 响应中
【发布时间】:2015-03-05 09:48:06
【问题描述】:

在我的一个 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 属性返回为 list 而不是 string 以便它变为:

{
    "name": "John", 
    "last_name": "Smith", 
    "age": 35, 
    "dl_url": [u'http://domain.com/file1', u'http://domain.com/file2']
}

最好的方法是什么?

请注意,我将链接作为models.TextField(null=True, blank=True) 实例存储在我的models.py 中。

提前谢谢你。

【问题讨论】:

    标签: python json django rest django-rest-framework


    【解决方案1】:

    试试这个:

    old_response = { “姓名”:“约翰”, "last_name": "史密斯", “年龄”: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(',')

    【讨论】:

    • 你必须通过序列化程序。它不像从一种类型“转换”到另一种类型那么简单......
    【解决方案2】:

    只需使用序列化器方法将其转换为列表。为此,请使用 drf 3.0 中引入的 to_representation 方法(在以前的版本中,它被称为 transform 或类似的东西)。

    def to_representation(self, instance): ret = super(UserSerializer, self).to_representation(instance) ret['dl_url'] = ret['dl_url'].split(',') return ret

    【讨论】:

    猜你喜欢
    • 2021-01-30
    • 2021-11-05
    • 2020-06-17
    • 2013-08-18
    • 1970-01-01
    • 2020-03-18
    • 2020-08-07
    • 2017-09-23
    • 2020-03-01
    相关资源
    最近更新 更多