Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django - Can you use property as the field in an aggregation function?

I know the short answer because I tried it. Is there any way to accomplish this though (even if only on account of a hack)?

class Ticket(models.Model):     account = modelfields.AccountField()     uuid = models.CharField(max_length=36, unique=True)     created = models.DateTimeField(auto_now_add=True)      class Meta:         ordering = ['created']      @property     def repair_cost(self):         # cost is a @property of LineItem(models.Model)         return self.lineitem_set.aggregate(models.Sum('cost')) 
like image 757
orokusaki Avatar asked Jun 18 '10 00:06

orokusaki


People also ask

Can you filter by property Django?

Nope. Django filters operate at the database level, generating SQL. To filter based on Python properties, you have to load the object into Python to evaluate the property--and at that point, you've already done all the work to load it.

What is the difference between aggregate and annotate in Django?

Aggregate calculates values for the entire queryset. Annotate calculates summary values for each item in the queryset.

What does aggregate do in Django?

When specifying the field to be aggregated in an aggregate function, Django will allow you to use the same double underscore notation that is used when referring to related fields in filters. Django will then handle any table joins that are required to retrieve and aggregate the related value.

How do you annotate in Django?

Appending the annotate() clause onto a QuerySet lets you add an attribute to each item in the QuerySet, like if you wanted to count the amount of articles in each category. However, sometimes you only want to count objects that match a certain condition, for example only counting articles that are published.


1 Answers

No. Anything that goes through a built-in manager has to be a real field, since they only touch the database. In order to work with a property they'd have to turn every record in the table into a model, then filter through them in Python.

like image 196
Ignacio Vazquez-Abrams Avatar answered Sep 25 '22 09:09

Ignacio Vazquez-Abrams