28

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'))
orokusaki
  • 55,146
  • 59
  • 179
  • 257

3 Answers3

29

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.

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
  • thanks. I thought that might be the case. I pictured `get all lineitemss and then call their cost property` but that would be so expensive :( – orokusaki Jun 18 '10 at 14:56
5

I have a similar scenario and want exactly the same feature. I solved it trivially with the following line:

...
return sum(lt.cost for lt in self.lineitem_set)
Fish Monitor
  • 4,155
  • 3
  • 32
  • 53
0

can use django-queryable-properties

hadi ahadi
  • 116
  • 1
  • 1
  • 6
  • 1
    While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. – Tyler2P Jul 31 '22 at 08:45
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - [From Review](/review/late-answers/32373781) – vimuth Aug 04 '22 at 08:32