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

久未见 提交于 2019-12-29 05:47:08

问题


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'))

回答1:


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.




回答2:


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)


来源:https://stackoverflow.com/questions/3066491/django-can-you-use-property-as-the-field-in-an-aggregation-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!