Skip to content

Django Tips and Tricks

Sam Kosman edited this page Jun 2, 2022 · 5 revisions

Patterns

Here are some design philosophies that Django has used when creating the framework.

Fat models, thin views

All business logic belongs in the "models", where "models" means models, managers and querysets. You should not put any domain logic in your views. This means that models should encapsulate all aspects of an object which is known as a the Active Record pattern.

Low Coupling and High Cohesion

The various layers described above shouldn't know about each other. For example, the database layer should know nothing about the view system. This means that when a change happens to say A, it allows B to change so that they are both the same (cohesive) rather than when A is changed, we also have to change B's behaviour (coupled).

DRY

Don't repeat yourself

Tips

Here is a good blog post that highlights some good tips for effectively developing in Django. If you don't want to read it all, here are some main points that apply for our application.

Don't put any domain logic into your views/serializers. Again goes with the pattern above.

Creating API Views

When creating an API view, use class-based API view as it provides a better separate of the HTTP methods. source

If you are creating a view that will be doing more than now thing, you should utilize the DRF Viewset. By utilizing the Generic Views and View Sets, DRF will implement various actions for you for your models. For example ModelViewSet will provide .list(), .retrieve(), .create(), .update(), .partial_update(), and .destroy() actions for you.

Model Relationships

If you need to create a relationship with a model that hasn't been defined yet, just use the name of the model rather than the model object itself. source

Ex.

from django.db import models

class Car(models.Model):
    manufacturer = models.ForeignKey(
        'Manufacturer',
        on_delete=models.CASCADE,
    )
    # ...

class Manufacturer(models.Model):
    # ...
    pass