社区所有版块导航
Python
python开源   Django   Python   DjangoApp   pycharm  
DATA
docker   Elasticsearch  
aigc
aigc   chatgpt  
WEB开发
linux   MongoDB   Redis   DATABASE   NGINX   其他Web框架   web工具   zookeeper   tornado   NoSql   Bootstrap   js   peewee   Git   bottle   IE   MQ   Jquery  
机器学习
机器学习算法  
Python88.com
反馈   公告   社区推广  
产品
短视频  
印度
印度  
Py学习  »  Django

请教Django REST framework的一些问题

codingchan • 10 年前 • 15223 次点击  

我想用DRF搭建Android App的后台,用json进行数据传递,但我对django以及DRF十分不熟,目前碰到的问题是:我通过建立model能够进行create、get list等一系列操作,但是问题是我该如何自定义其返回的json数据呢?比如我创建了一篇post,后台返回的json数据是:

{title: 'title', content: 'content'}

但是我希望获得的形式是:

{status_code: '100', msg: 'msg', data: {{title: 'title', content: 'content'}}

请问这该如何实现?或者说在这种情况下DRF本身就是个多余的框架?谢谢!

Python社区是高质量的Python/Django开发社区
本文地址:http://www.python88.com/topic/596
 
15223 次点击  
文章 [ 11 ]  |  最新文章 10 年前
the5fire
Reply   •   1 楼
the5fire    10 年前

恩,约定好个格式就行,传递是字符串,或者转成时间戳也行。

codingchan
Reply   •   2 楼
codingchan    10 年前

我觉得我犯了一些低级错误……客户端与服务器之间用UTC时间传递即可,到客户端转换为本地时间显示即可

codingchan
Reply   •   3 楼
codingchan    10 年前

@the5fire 谢谢,我也发现了><,另外想问下,django和java如何进行时间传递?后台保存时间我是直接用Datetime类型,但在传递给前端时遇到了问题:无法直接通过gson解析保存,应该在后端将时间转换为时间戳再传么?那么如何传递时区呢?或者有更好的解决办法?

Any help would be appreciated.

the5fire
Reply   •   4 楼
the5fire    10 年前

restful 通过http的状态码来做为操作结果的执行状态的,比如访问/post/<id>/ 返回404 就是不存在,200 就是存在, 你发送一个post请求到 /post/ 接口上,返回201 表示创建成功,返回403表示没有权限之类的。

rest framework 返回的数据其实是一个分页的结果,你可以通过定制paginationSerializer来完成你的需求:

https://github.com/tomchristie/django-rest-framework/blob/master/rest_framework/pagination.py#L88

Py站长
Reply   •   5 楼
Py站长    10 年前

@codingchan 赞的

codingchan
Reply   •   6 楼
codingchan    10 年前

@Django中国社区 目测可以,我还在尝试:)

Py站长
Reply   •   7 楼
Py站长    10 年前

@codingchan 可以将 total、errorcode 放到 data 里面吗

codingchan
Reply   •   8 楼
codingchan    10 年前

@Django中国社区 thx! 请参见我的上一篇回复。

codingchan
Reply   •   9 楼
codingchan    10 年前

@the5fire 十分感谢您的回复!我通过查阅DRF的文档发现可以通过pagination和renderer处理返回data,这解决了我的一部分问题。看了您的回复之后我的问题是如果restful api无法提供类似total、errorcode之类的参数,那么它又如何有效地运行?谢谢。

Py站长
Reply   •   10 楼
Py站长    10 年前

http://www.django-rest-framework.org/

正如楼上所说,你要的返回是特殊定制,与DRF定义的不一样,也就是说协议不一样。我的理解是,如果你用了DRF,你就必须接受它的协议 。

the5fire
Reply   •   11 楼
the5fire    10 年前

你这种需求不算是restful api了。

如果真的要这么做,那只能是hack了