DEV Community

Cover image for Using @property decorator in Django
Rashid
Rashid

Posted on • Edited on • Originally published at thepylot.dev

Using @property decorator in Django

This post cross-published with OnePublish

I will show you how to use @property decorator in Django models to make code clean and optimized. Instead of adding extra fields to our model, we can define a custom property that will use already existing fields to return the required data.

Example Scenario

We have a model named Post with the following fields:

class Post(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()
Enter fullscreen mode Exit fullscreen mode

Assume that we also need a field to let us know which post names include specific prefixes such as example_ and another one for getting comments of a particular post.

It will be a bad approach if we continuously use if statements and call Comment.objects.filter(post_id=post.id) queryset multiple times in different parts of the codebase.

Creating property for Django model

Instead, we can create a property that will behave like a field of our Django model but in a more flexible way.

class Post(models.Model):
    name = models.CharField(max_length=255)
    description = models.TextField()

    @property
    def has_prefix(self):
        return "_example" in self.name

    @property
    def comments(self):
        if self.id:
            return Comment.objects.filter(post_id=self.id)
        return Comment.objects.none()
Enter fullscreen mode Exit fullscreen mode

Consider the naming of properties, it should be meaningful and straightforward without using prefixes like get_comments or similar.

So you can call these properties like below:

post = Post.objects.first()

if post.has_prefix:
  # do something
  return post.comments
Enter fullscreen mode Exit fullscreen mode

Support 🌏
If you feel like you unlocked new skills, please share them with your friends and subscribe to the youtube channel to not miss any valuable information.

Top comments (0)