Problem details

Fat models, thin views is an adage commonly told to Django beginners. Ideally, your views should not contain anything other than presentation logic.

However, over time, pieces of code that cannot be placed anywhere else tend to go into models. Soon, models become a dump yard for the code.

Consider refactoring out a Service object if your model contains code for any of the following:

  1. Interactions with external services, for example, checking whether the user is eligible to get a SuperHeroProfile with a web service
  2. Helper tasks that do not deal with the database, for example, generating a short URL or random captcha for a user
  3. Making a short-lived object without a database state, for example, creating a JSON response for an AJAX call
  4. Functionality spanning multiple model instances yet do not belong to anyone
  5. Long-running tasks such as Celery tasks

Models in Django follow the Active Record pattern, that is, each class instance corresponds to a row in the database table. Ideally, they encapsulate both database access and application (or domain) logic. However, keep the application logic minimal.

While testing, if we find ourselves mocking the database even while not using it, then we need to consider breaking up the model class. A Service object is recommended in such situations.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.188.115.118