django models = business logic + data access? Or data access layer should be separated out from django model? django models = business logic + data access? Or data access layer should be separated out from django model? django django

django models = business logic + data access? Or data access layer should be separated out from django model?


After three years of Django development, I've learned the following.

The ORM is the access layer. Nothing more is needed.

50% of the business logic goes in the model. Some of this is repeated or amplified in the Forms.

20% of the business logic goes in Forms. All data validation, for example, is in the forms. In some cases, the forms will narrow a general domain (allowed in the model) to some subset that's specific to the problem, the business or the industry.

20% of the business logic winds up in other modules in the application. These modules are above the models and forms, but below the view functions, RESTful web services and command-line apps.

10% of the business logic winds up in command-line apps using the management command interface. This is file loads, extracts, and random bulk changes.

It's very important that view functions and RESTful web services do approximately nothing. They use models, forms, and other modules as much as possible. The view functions and RESTful web services are limited to dealing with the vagaries of HTTP and the various data formats (JSON, HTML, XML, YAML, whatever.)

Trying to invent Yet Another Access Layer is a zero-value exercise.


The answer depends on the requirements of your application.

For applications which will always use relational databases and can be coupled with a specific ORM, you do not need to separate data access and models. Django ORM is based on the active record design pattern, which supposes data access and model are together. Pro is simplicity, con is less flexibility.

Separating data access and model is only necessary when developer wants to uncouple completely data access layer and business logic. You can do it with the data mapper design pattern. Some ORMs support this design pattern, such as SQLAlchemy. Pro is more flexibility, con is more complexity.

I recommend the book "Patterns of Enterprise Application Architecture" written by Martin Fowler for more details.