What does Django’s @property do?
Django’s @property
is a Python decorator that allows you to define a method as a property, which means that you can access it like an attribute, without calling it a method. The @property decorator is used to create getter methods in a class.
If you want to know about it properly then just check out this example. It will help you to understand what does @property
actually do.
Let’s consider a model class named Employee
with three fields: first_name
, last_name
and full_name
(the concatenation of first_name
and last_name
fields).
class Employee(models.Model): first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) @property def full_name(self): return f"{self.first_name} {self.last_name}"
In the above example, the full_name
method is decorated with the @property
decorator, which allows it to be called an attribute.
Read More: How to create the Bangladesh flag using HTML and CSS
You can now access the full_name
property on an instance of the Employee
model as shown below:
employee = Employee.objects.get(id=1) print(employee.full_name) # Output: John Doe
Here, we are calling the full_name
property of the employee
object directly as if it were an attribute. The full_name
property method is automatically called behind the scenes and the result is returned.
The @property
decorator provides a way to encapsulate class properties and make the code more readable and expressive. It can also be used to perform additional operations before returning the value of the property.