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

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

问题描述

我是Django Rest Framework的新手。使用 serializer views 可以轻松实现CRUD。当逻辑增加时,在序列化器视图中写逻辑的位置就很令人困惑。

有些开发人员确实喜欢厚实的序列化程序和精简视图,而有些开发人员更喜欢厚实的序列化程序和精简视图。

也许这不是一个大问题,我认为这取决于开发人员是否编写更多内容在视图序列化器上,但是作为新手,您的建议是什么?我应该在视图序列化器上写更多吗?

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时,您可以根据需要模拟这些buiness逻辑。

  5. 在多个位置重用任何逻辑。

  1. Makes the code cleaner(no thick and thin stuff).
  2. Writing tests for those business logic is easier.
  3. You can use that this business logic service in both view and serializer, depending on your need.
  4. while testing APIs, you can mock those buiness logic if needed.
  5. Reuse any logic in multiple places.

一个例子是这样的:

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天全站免登陆