Common Models in Django and the DRF

Django is a great way to handle the most repetitive, boring parts of backend development. The Django Rest Framework (DRF) takes this one step further and adds standard serializers, permissions, and more.

However, in the face of how varied web backends can be, certain things are left for the implementer to discover.

One thing discovered very early on was the need to standardize our model, APIs contain a lot of repetition, and if you’re lucky you get the opportunity to see and code around the patterns that describe your data.

For my projects I noticed a constant need of several things:

  • A unique identifier for the object.
  • When the object was created.
  • Which user created it.
  • When the object was last updated.
  • Which user updated it.

The first bullet point, an id, should come as a surprise to no one. It’s included in the standard django model. The others are very useful for auditing purposes, and can be used for a myriad of other goals. From this we developed a common collection of django classes.

What inheriting from these classes gives you is a way to automatically keep track of who is creating or editing data through your API. No need for an author or a last_edited_by field ever again! Let’s show an example of inheriting from these classes.

This general approach, while being against the common python principle of composition over inheritance, can give your ORM a common pattern among its api, which is a great thing to start with for any project.