user9252255
user9252255

Reputation:

Django models: @property

Is there a 'rule' when to add @property and when not? Both works fine, so I am looking for another rule or best practice.

view.py

order_items_qty = self.ticket.sold_tickets

vs.

order_items_qty = self.ticket.sold_tickets()

models.py

@property
def sold_tickets(self):
    return self.attendees.filter(canceled=False).count()

Upvotes: 1

Views: 3819

Answers (2)

Gokhan Sari
Gokhan Sari

Reputation: 7944

Quoting directly from docs:

A property object has getter, setter, and deleter methods usable as decorators that create a copy of the property with the corresponding accessor function set to the decorated function.

In your example, there is no difference and AFAIK there isn't a rule when to use a class method or property, it is up to you. Personally, when working with Django's models I leave them methods in order not to confuse my custom model related calculations with model's fields.

# i immediately realize this is a direct field of model, will be fetched from database
concert.created_at

# and this one includes custom calculations
sold_tickets = concert.get_tickets_sold()

Upvotes: 2

AKX
AKX

Reputation: 168967

My rule of thumb is to use functions instead of properties when the value might require significant computation or, say, several queries.

Users of a Python API will usually not expect what looks like a simple attribute access to take a long time.

(By the way, depending on your app and requirements, there's also @cached_property, which is computed only once per instance and cached thereafter. However, in your case, if some of the attendees change their cancellation status, those changes would not be reflected immediately.)

Upvotes: 3

Related Questions