Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django models: when should I use the @property decorator for attributes?

Tags:

python

django

I would like to know what would be the best practice. I have been using the @property decorator a lot because it allows me to avoid creating custom context variables when I want to display something related to a model instance on a template.

I feel like my models are too big. Is this ok?

like image 817
sebasuy Avatar asked Apr 20 '12 01:04

sebasuy


People also ask

What does @property decorator do?

The @property is a built-in decorator for the property() function in Python. It is used to give "special" functionality to certain methods to make them act as getters, setters, or deleters when we define properties in a class.

What is the purpose of @property Python?

A python @property decorator lets a method to be accessed as an attribute instead of as a method with a '()' . Today, you will gain an understanding of when it is really needed, in what situations you can use it and how to actually use it.

What does @property do in Django?

In Python, @property is a built-in decorator that creates and returns a property object. The @property decorator is internally taking the bounded method as an argument and returns a descriptor object.

What is @property decorator in Python?

@property decorator is a built-in decorator in Python which is helpful in defining the properties effortlessly without manually calling the inbuilt function property().


1 Answers

It's not a problem unless you find yourself writing exactly the same code on model after model. At that point you should consider writing a template tag that takes the model as a parameter instead.

like image 117
Ignacio Vazquez-Abrams Avatar answered Oct 11 '22 15:10

Ignacio Vazquez-Abrams