Member-only story
Django Model Decorators — Tips and Tricks With Implementation
Learn to write functionality once and share between models or applications

Motivation and Roadmap
We intend to apply functionality to a Django model that can be replicated and easily applied to multiple models. We will touch on examples and work through how to solve them by doing the following:
- adding fields to the model
- adding properties to the model
- adding a factory decorator that attaches a default serialiser for REST framework usage
Before we start solving the above problems, let’s quickly refresh a few points on decorators and Django models. If you are completely comfortable with these, feel free to skip ahead.
Decorators: Refresher
Decorators are functions applied to functions (or classes), leading to enriched functionality. In essence, they are syntactic sugar for applying functions to functions, “wrapping” a function into another one.
There are numerous great tutorials on decorators out there that explain how they work, so for deep understanding please consult those.
For the sake of this article, we shall highlight one very important piece to understand: decorators act on functions/classes to put a layer around them.
Take a look at this decorator that acts before and after the execution of the wrapped function. Then see two equivalent options on how to use it. Here’s the code:
Running either will lead to the same output, as shown below:
In [2]: func1("Hello World!") # same for func2(...)
I cam do something before the function call!
Hello World!
I can do something after the function call!