Learn Django

Adding Business Logic to Models

In the next lesson you'll learn how to add code to the application that uses Stripe to process a customer's credit card. A good question to ask is, where should this code be placed? The good news is that there are options. Here are several that could be considered:

  • In the view. In our example, the code could be added to the subscriber_new() view.
  • In a separate file and imported. We could create a file in the app directory, say payment_processor.py, and add our code there. We'd then have to import that file into the subscriber_new() view.
  • On the model itself. In this case the code could be added to the Subscriber model as a method.

The recommended best practice is the last one; apply code to the model itself. This concept is referred to as fat models. When using fat models, it implies that our views are thin, meaning that we don't add too much code to them.

Why use the fat model method? This method is recommended because it makes it easy to reuse code. If we add credit card processing to the model, we can execute it from any view.

Having a rule like this will also make it easier to organize and read code.

Track your progress with a free account