首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Django REST框架:非模型序列化程序

Django REST框架:非模型序列化程序
EN

Stack Overflow用户
提问于 2012-11-28 18:35:23
回答 1查看 49.4K关注 0票数 175

我是Django REST框架的初学者,需要你的建议。我正在开发一个web服务。服务必须提供到其他服务的REST接口。我需要实现的REST接口并不直接使用我的模型(我指的是get、put、post、delete操作)。相反,它为其他服务提供了一些计算结果。在请求时,我的服务进行一些计算并返回结果(不将结果存储在自己的数据库中)。

下面是我对REST接口如何实现的理解。如果我错了,请纠正我。

  1. 创建进行计算的类。将其命名为'CalcClass‘。CalcClass在其工作中使用了这些模型。

代码语言:javascript
复制
- Params necessary for the calculations are passed to the constructor.  
- Implement the calc operation. It returns results as 'ResultClass'.  

  1. Create ResultClass。

代码语言:javascript
复制
- Derived from object.  
- It just only has attributes containing the calc results.  
- One part of the calc results is represented as tuple of tuples. As I understand, it would be better for further serialization to implement a separate class for those results and add list of such objects to ResultClass.  

用于ResultClass.的

  1. 创建序列化程序

代码语言:javascript
复制
- Derive from serializers.Serializer.  
- The calc results are read-only, so use mostly Field class for fields, instead of specialized classes, such as IntegerField.  
- I should not impl save() method neither on ResultClass, nor on Serializer, because I am not going to store the results (I just want to return them on request).  
- Impl serializer for nested results (remember tuple of tuples mentioned above).  

  1. 创建视图以返回计算结果。

代码语言:javascript
复制
- Derive from APIView.  
- Need just get().  
- In get() create CalcClass with params retrieved from the request, call its calc(), get ResultClass, create Serializer and pass the ResultClass to it, return Response(serializer.data).  

  1. URLs

代码语言:javascript
复制
- There is no api root in my case. I should just have URLs to get various calc results (calc with diff params).  
- Add calling format\_suffix\_patterns for api browsing.  

我错过了什么吗?这种方法总体上是正确的吗?

EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13603027

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档