Hello Guys,
In Django models, the @property
decorator is used to define a read-only property for a model’s instance. This allows you to create a property that is calculated dynamically based on the model’s fields or other attributes
Benefits Of the use of @property
- Abstraction of Complex Logic: Encapsulate complex logic or calculations in a clean, readable way.
- Avoid Unnecessary Database Queries: Computed properties are evaluated in Python, reducing the need for additional database queries.
- Dynamic Computed Fields: Easily compute fields on-the-fly based on other attributes.
How to use @property
In the case you have a contestant model
class Contestant(models.Model):
first_name = models.CharField(max_length=200, blank=True, null=True)
last_name = models.CharField(max_length=200, blank=True, null=True)
vote = models.IntegerField(max_length=200, blank=True, null=True)
date_created = models.DateTimeField(auto_now_add=True)
@property
def full_name(self):
# function to return the full name of the user
return f"{self.first_name} {self.last_name}"
@property
def percentage_vote(self):
# this is to return the percentage value of each user without the need to calculate it at the views section
total_vote = Contestant.objects.all().aggregate(Sum("vote"))[
"vote__sum"
]
percentage = (self.vote/total_vote) * 100
return percentage
to keep your code clean its good to be using these in django.