Django Rest框架业务逻辑

时间:2015-05-12 17:25:05

标签: python django django-rest-framework business-logic

我正在尝试使用 Django Rest Framework 创建一个后端,并且我正在尝试确定将业务逻辑放在何处。它会进入views.py吗?我想创建更复杂的服务,而不仅仅是获取对象列表或抓取一个特定对象。任何指导将不胜感激,谢谢。我意识到在一个通用的Django项目中有关于业务逻辑的讨论,但我特别询问了django rest框架。

2 个答案:

答案 0 :(得分:0)

我想这是Rest Framework中的一种设计模式。这是我如何在基于Rest Framework的API中使用分层方法的详细概述!

为了易于维护,它更加分层,最重要的是利用了设计模式和GRASP Principal!

分层方法包级别视图

enter image description here

进一步分类:

enter image description here enter image description here

现在是我如何遍历图层的示例:

  1. 已向example.com/Customer/profile发出请求 @ project / urls.py enter image description here

  2. 请求被转发到相应URL的层(@ app / urls / Customer_Url) The Request is forwarded to the Respective URL's Layer

  3. URL将其传递到相应的视图集 (@ app / Viewsets / Customer_Viewsets / Customer_Signup.py) enter image description here

  4. 这是一个发布请求,(在此示例中,我假设)被转发到业务逻辑层 (@ app / BusinessLogicLayer / BLL.py) enter image description here

  5. 业务逻辑层具有抽象实现(充当IBLL的接口),并将请求转发到相应的方法,以检查我的所有业务规则! (@ app / BusinessLogicLayer / SUB_BLL / Customer / *) enter image description here

  6. 然后将请求转发到将用户数据存储在数据库中的数据访问层。等等! (@ 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.