django - 如何在 Django 中实现服务层?

标签 django django-models django-rest-framework django-views

我在这篇文章中看到1以及在此视频中 2这对于使用服务层在 Django 中构建您的 REST 应用程序非常有帮助,因为将您的业务逻辑放在模型层或 View 层中并不是最佳选择。你能和我分享一些简单的 Django 服务模型吗?

最佳答案

最好的基于 DRF 的企业应用程序是在 Django 和 DRF 上使用以下结构开发的:-

  • 代理模型(即目的 - 您的默认模型保持干净,所有基于对象的
    业务逻辑在这里。)
  • 自定义管理器(即目的 - DAO(数据访问逻辑)在这里,我们也可以实现
    代码的可重用性)
  • 服务层(即目的 - 核心业务逻辑在这里,因此您的 View 类
    更具可读性)

  • 服务层示例:
    class RecoInfoService():
    
        def get_initiated_reco_detail(self, request, id):
            obj = RecoInfoProxy.objects.get_initiated_reco_by_id(id=id)
            serial_data = GetRecoInfoSerializer(obj)
            return Response(serial_data.data, status=status.HTTP_200_OK)
    
    
        def initiate_reco(self, request):
            line_items_service = LineItemsService()
            print(request.data, type(request.data),"in INITIA")
            serial_data = RecoInfoSerializer(data=request.data, many=True, context={'request':request})
            if serial_data.is_valid(raise_exception=True):
                with transaction.atomic(), reversion.create_revision():
                    createdObj = reversion_post(request, serial_data)
                    self.trigger_reco_initiation_notification(createdObj)
                    line_items_service.prefetch_reco_initiation_lineitems(createdObj)
                return createdObj
    
    现在来自您的 views.py ,调用此服务方法为:
    class RecoInfoView(views.APIView):
    
        def post(self, request, **kwargs):
            operation = kwargs.get('operation')
            initiate_reco_service = RecoInfoService()
            if operation == 'request':
                reco_info_obj = initiate_reco_service.initiate_reco(request)
                return Response('msg  : Initiate Reco Successfull')
    

    关于django - 如何在 Django 中实现服务层?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62740603/

    相关文章:

    django - 为什么 Django Swagger 不显示具有 IsAuthenticated 权限的 url 的文档?

    Django - 过滤模板中的RelatedManager _set?

    python - Django + Pytest + Selenium

    python - 使用 annotate 连接 3 个表获取数据

    python - Django 序列化程序嵌套创建 : How to avoid N+1 queries on relations

    django - 如何在 Django Rest Framework (DRF) 中控制版本控制

    python - 有权在 Django 管理中仅修改模型的一个字段的用户

    jquery - django jquery 就绪事件未触发

    Django - 不同类型的用户配置文件

    python - dir(models.Model.Blog) 不显示 Blog 的类变量(Fields),为什么?