DEV Community

Cover image for Using @property decorator in Django
Rashid
Rashid

Posted on β€’ Edited on β€’ Originally published at thepylot.dev

7

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.

AWS Security LIVE!

Join us for AWS Security LIVE!

Discover the future of cloud security. Tune in live for trends, tips, and solutions from AWS and AWS Partners.

Learn More

Top comments (0)

πŸ‘‹ Kindness is contagious

Please leave a ❀️ or a friendly comment on this post if you found it helpful!

Okay