Django Model Decorators — Tips and Tricks With Implementation | by Tamas K Stenczel | Mar, 2022

Study to put in writing performance as soon as and share between fashions or purposes

Photograph by Stephen Hamilton on Unsplash | Altered

We intend to use performance to a Django mannequin that may be replicated and simply utilized to a number of fashions. We are going to contact on examples and work by easy methods to clear up them by doing the next:

  1. including fields to the mannequin
  2. including properties to the mannequin
  3. including a manufacturing facility decorator that attaches a default serialiser for REST framework utilization

Earlier than we begin fixing the above issues, let’s rapidly refresh a number of factors on decorators and Django fashions. If you’re fully comfy with these, be happy to skip forward.

Photograph by Sincerely Media on Unsplash

Decorators are capabilities utilized to capabilities (or lessons), resulting in enriched performance. In essence, they’re syntactic sugar for making use of capabilities to capabilities, “wrapping” a operate into one other one.

There are quite a few nice tutorials on decorators on the market that designate how they work, so for deep understanding please seek the advice of these.

For the sake of this text, we will spotlight one crucial piece to know: decorators act on capabilities/lessons to place a layer round them.

Check out this decorator that acts earlier than and after the execution of the wrapped operate. Then see two equal choices on easy methods to use it. Right here’s the code:

Working both will result in the identical output, as proven under:

In [2]: func1("Good day World!") # similar for func2(...)
I cam do one thing earlier than the operate name!
Good day World!
I can do one thing after the operate name!

Django fashions are outlined as lessons which can be used for outlining the database construction in addition to offering an summary interface to the underlying database. There’s a good bit of “magic” taking place within the background when these are used for instance when migrations are made. We are going to perceive how a few of these work.

See this instance:

from django.db import fashionsclass DummyModel(fashions.Mannequin):
quantity = fashions.IntegerField()

Which is able to result in a desk in your database with an integer column and the ID (.pk) after all.

Let’s say we need to put a area on the mannequin, how to try this in a decorator? For a easy class, this may be:

If you happen to do this with a Django mannequin, then it doesn’t work! Properly, no error is thrown however there’s additionally nothing taking place. For instance, with this code:

Is equal to the above, the textual content area 1 shouldn’t be created and won’t be added to the database. However why is that?

There may be extra to a mannequin’s creation than including members to a Python class: the magic occurs when the sphere object’s contribute_to_class technique is used. Let’s see how that works and what we must always do with the above snippet.

This does what we would like it to: create a UUID area on the mannequin which can present up within the migrations as effectively.

That is an alternative choice to utilizing summary mannequin lessons to derive from, and is offered as a alternative for the programmer. Let’s see what extra we are able to do with these decorators.

Let’s say there’s some performance like widespread derived parameters that you simply need to add to a number of fashions. Let’s see how we are able to prolong the above with properties as effectively.

For instance, for those who needed to trace the creation and alter occasions of a mannequin, and know the age of the mannequin within the database, then you are able to do the next:

It will apply a creation date and modification time area to the mannequin. The creation date is recorded on the time of creation and can’t be modified afterward, whereas the modification time is being up to date each time one thing modifications the mannequin.

A caveat of the replace time is that it solely works for Python code altering the mannequin, not when direct SQL is evaluated on the database [1]. This is because of how Django is dealing with modifications and triggers indicators [2].

The age of the mannequin is a derived parameter and will depend on the present time, so that’s applied as a property on the mannequin object.

For readability, that is equal to having these fields and properties written to the category immediately (see [1] as effectively):

n.b. This design is once more a alternative, there are different strategies to get to the identical end result as effectively, for instance by creating an summary mannequin class to derive from (probably utilizing a number of inheritances). This alternative could make the code maybe extra readable and chic.

Within the case of working with REST frameworks, one may have many serializers, sand a few of these are fairly easy and comparable. Here’s a trick so as to add a default easy serialiser to the fashions, which could be imported with them. This is kind of like a serializer manufacturing facility

Right here is an easy serializer that may be created over and over for fashions:

After about two, one ought to create a manufacturing facility operate that creates the serializer for any mannequin given. We will additionally do that with a decorator on the mannequin itself:

This may be prolonged in some ways, for instance offering generic APIViews as effectively, or including extra performance to them in case that’s utilized by many fashions.

We now have seen easy methods to apply decorators to Django fashions, unlocking all kinds of Pythonic performance to be added. For many instances, these are selections that one could make, or resolve to get to an analogous end result otherwise.

Thanks very a lot for studying this text. I hope you may have realized or seen one thing new!

Photograph by Michelle Ding on Unsplash

References:

More Posts