簡體   English   中英

如何將列表值放入Django的rest框架json響應中

[英]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.pymodels.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM