我正在尝试使用 Django Rest Framework 创建一个后端,并且我正在尝试确定将业务逻辑放在何处。它会进入views.py吗?我想创建更复杂的服务,而不仅仅是获取对象列表或抓取一个特定对象。任何指导将不胜感激,谢谢。我意识到在一个通用的Django项目中有关于业务逻辑的讨论,但我特别询问了django rest框架。
答案 0 :(得分:0)
我想这是Rest Framework中的一种设计模式。这是我如何在基于Rest Framework的API中使用分层方法的详细概述!
为了易于维护,它更加分层,最重要的是利用了设计模式和GRASP Principal!
分层方法包级别视图
进一步分类:
现在是我如何遍历图层的示例:
URL将其传递到相应的视图集
(@ app / Viewsets / Customer_Viewsets / Customer_Signup.py)
这是一个发布请求,(在此示例中,我假设)被转发到业务逻辑层
(@ app / BusinessLogicLayer / BLL.py)
业务逻辑层具有抽象实现(充当IBLL的接口),并将请求转发到相应的方法,以检查我的所有业务规则! (@ app / BusinessLogicLayer / SUB_BLL / Customer / *)
然后将请求转发到将用户数据存储在数据库中的数据访问层。等等! (@ app / DataAccessLayer / DAL.py)
答案 1 :(得分:0)
也许这是一个有点古怪的方法,但是我认为通过在其中添加方法将逻辑包装到序列化器中非常有帮助。
例如
序列化器:
class OrderSerializer(serializers.ModelSerializer):
class Meta:
model = Order
fields = (
'id',
'total',
'discount',
)
def calculate_discount(self, whatever_params):
# calculate discount if you need... and return it
def calculate_tax(self, whatever_params):
# calculate tax amount if you need...and return it
def calculate_grand_total(self, whatever_params):
# calculate grand total if you need and return it
def create(self, validated_data):
# You can make an order by applying
# some logic in the calculation method.
# Maybe by adding a bit of the context
# you sent as parameters from view.