How can I implement service layer in Django?

Viewed 5630

I see in this article 1 and also in this video 2 that is very helpful to build your REST application in Django using a service layer because put your business logic in Model Layer or in View Layer isn't the best choice. Can you share with me some simple models of services in Django ?

1 Answers

The best DRF based enterprise Applications are developed with following structure over Django and DRF :-

  • Proxy Models (i.e purpose - your default model remains clean, all your object based business logic goes here.)
  • Custom Managers (i.e purpose - DAO (Data Access Logic) goes here, also we can achieve
    re-usability of code)
  • Service Layer (i.e purpose - core business logic goes here, therefore your views class has more readability)

Example For Service Layer :

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

Now from your views.py, call this service methods as:

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')
Related