Django rest 框架在serializer.py 或views.py 中哪里编写复杂的逻辑? [英] Django rest framework where to write complex logic in serializer.py or views.py?

查看:15
本文介绍了Django rest 框架在serializer.py 或views.py 中哪里编写复杂的逻辑?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Django Rest 框架的新手.使用 serializerviews 一个简单的 CRUD 很容易.当逻辑增加时,在serializerviews中写逻辑的地方很混乱.
一些开发人员确实更喜欢粗序列化器和细视图",而一些开发人员更喜欢粗视图和细序列化器".
也许这不是一个大问题,我认为开发人员是否在 viewsserializer 上编写更多内容取决于开发人员,但是作为新手,您应该遵循什么建议?我应该在 views 还是 serializer 上写更多?
Django View Template 上有很多答案,但找不到满意的 Django Rest Framework 答案.
经验丰富的开发人员的想法将受到高度赞赏.谢谢.

I am new to Django Rest Framework. Using serializer and views a simple CRUD is easy. When the logics increase, it is quite confusing where to write logics in serializer or views.
Some developers do prefer "Thick serializer and thin views" and some developers "Thick views and thin serializer".
Maybe this is not a big issue and I think it is up to the developer whether to write more on views or serializer, but as a newbie what will be your suggestion to follow? Should I write more on views or serializer?
There are many answers on Django View Template but can not find a satisfying answer for Django Rest Framework.
Thoughts of experienced developers will be highly appreciated. Thank you.

推荐答案

我个人更喜欢将业务逻辑与视图和序列化程序分开.我通常创建一个包含业务逻辑的新类,它可以根据需要在序列化程序和视图中使用.基本上我把它当作一种服务.原因是:

Personally I prefer to have the business logic separated from both view and serializer. I usually create a new class with the business logic which can be used in both serializer and view based on necessity. Basically I treat it as a service. Reason for that is:

  1. 使代码更简洁(没有粗细的东西).
  2. 为这些业务逻辑编写测试更容易.
  3. 您可以根据需要在视图和序列化程序中使用此业务逻辑服务.
  4. 在测试 API 时,您可以根据需要模拟这些业务逻辑.
  5. 在多个地方重复使用任何逻辑.

一个例子是这样的:

class BusinessLogicService(object):

    def __init__(self, request):
       self.request = request

    def do_some_logical_ops(self, data_required_one, data_required_two):
        # do processing
        return processed_data

序列化程序中的示例用法:

Example usage in serializer:

class SomeSerializer(serializer.Serialize):
     ...
     def create(self, validated_data):
         business_logic_data = BusinessLogicService(self.request).do_some_logical_ops(**validated_data)
         return Model.objects.create(**business_logic_data)

这篇关于Django rest 框架在serializer.py 或views.py 中哪里编写复杂的逻辑?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆