将查询放在models.py或views.py中会更好吗?

时间:2017-08-09 07:51:09

标签: django

我想进行查询

query = Rating.objects.filter(human=pk)

friendliness = query.aggregate(Avg('friendliness'))
punctuality = query.aggregate(Avg('punctuality'))
knowledge = query.aggregate(Avg('knowledge'))

并在我的HTML中显示。最好将它放在views.py中,还是最好将它放在models.py?

1 个答案:

答案 0 :(得分:1)

我认为这最适合models.Manager

class RatingManager(models.Manager):
    ...
    def aggregate_by_friendliness(self, human):
        return self.filter(human=human).aggregate(Avg('friendliness'))

class Rating(models.Model):
    ...
    objects = RatingManager()

所以你可以像这样重用它:

friendliness = Rating.objects.aggregate_by_friendliness(human=pk)