[Answered ]-Django: Business logic inside the models?

1👍

Both approaches have their own advantages depending on the specific requirements and design of your app:

  1. Model property:

    • The mark_as_active is a method of the model and encapsulates the logic within the model itself; the advantage is that the logic is closely tied to the model, making it convenient and intuitive to use. It promotes a more object-oriented approach.
    • This solution works well if the activation logic is directly related to the internal state and behavior of the model. As an example, in this case you can easily take advantage of some Django features like the @cached_property decorator.
    • It keeps the code modular and reduces the need for additional services or external functions (you can always call the MyModel.mark_as_active method)
  2. Separate module:

    • The activation logic is encapsulated in a separate service function and the business logic is separated from the model itself, promoting separation of logic.
    • The service function can be more reusable and can be used from different parts of your application if needed (for example it’s easy to unit test).
    • It allows for more flexibility in terms of organizing and structuring your codebase and works well if the activation logic involves additional operations beyond the scope of your model, such as calling additional models or implementing other complex logic.

Considerations:

  • If the activation logic is simple and closely tied to the internal state of your model, adding the method directly to the model (approach 1) can provide a clean and effective implementation.
  • If the activation logic involves additional operations or requires interactions with other models or external services, separating it into a service function (approach 2) can provide better separation of logic and maintainability.

In practice, you can consider a hybrid approach, where you start with approach 1 and then refactor to approach 2 if the activation logic becomes more complex or the requirements change.

👤Dos

Leave a comment