Django rest框架在哪里可以在serializer.py或views.py中编写复杂的逻辑? [英] Django rest framework where to write complex logic in serializer.py or 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:
- 使代码更干净(没有粗细的东西)。
- 为这些业务逻辑编写测试更加容易。
- 您可以根据需要在视图和序列化程序中使用该业务逻辑服务。
- 在测试API时,您可以根据需要模拟这些buiness逻辑。
- 在多个位置重用任何逻辑。
- Makes the code cleaner(no thick and thin stuff).
- Writing tests for those business logic is easier.
- You can use that this business logic service in both view and serializer, depending on your need.
- while testing APIs, you can mock those buiness logic if needed.
- 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屋!