2

I was wondering which is the correct way to use models(ORM) of mongonegine python.

I have a coupon class which directly maps to mongodb json document.

class Coupon(Document):
    __collection__ = 'coupon'

    coupon = StringField()
    points = IntField()

    @property
    def increment(self):
        self.points += 1

    @property
    def decrement(self):
        self.points += 1

The thing that i find wrong with above is , we are binding behaviour to database access layer, which i think is not correct way of doing things (I might be completely wrong).

Another way (Which I think makes more sense) is delegating business logic to some other layer commonly called as service layer:

models.py

class Coupon(Document):
    __collection__ = 'coupon'

    coupon = StringField()
    points = IntField()

services.py

from models import Coupon

def increment_points(c_id):
   c_id.points+=1

I want to know which is the correct way of doing things(assuming we have lots of models).

Question: should we bind behaviors to models or use a service layer for business logic?

NOTE: I have added tag python because I have seen many people binding behaviours and business logic to the DB access layer in their codebases.services are rarely heard of in any of the tutorials about python web frameworks. but its very common in Java and PHP.

anekix
  • 2,393
  • 2
  • 30
  • 57
  • 1
    I think you can take a look at this https://stackoverflow.com/questions/12578908/separation-of-business-logic-and-data-access-in-django discussion – T.Tokic Apr 08 '18 at 11:53
  • @T.Tokic thanks, even there it's suggested to use service layers in accepted answer.so is my reasoning correct with the first design being wrong? – anekix Apr 08 '18 at 11:55

1 Answers1

0

You can find great heuristics how to structurize project responsibilities in DDD (Domain Driven Design) approach. The project usually has domain logic (some business rules and actions) and application logic (orchestration of the business process, like executing domain objects methods, database access, external service requests, etc.). Domain logic should be implemented in entites and domain services, while application logic should be implemented within application services.

You said that behaviour should not be bind to database access layer. You are right, but the solution is not to move business logic to service layer (application layer), but to seperate domain and persistance models (and keep domain logic in domain model). How to do it in python? You can find solutions here:

jorzel
  • 1,216
  • 1
  • 8
  • 12