在Django中添加查询集中的所有值

时间:2017-06-08 17:08:42

标签: django python-3.x

我正在写一个django应用程序,它有两个类:一个评论,以及对该评论的回复。答复存储在评论中的ManyToMany字段中。

这是我的评论课程:

SHOW GRANTS

这是我的回复课:

class Review(models.Model):
    title = models.CharField(max_length = 30)
    replies = models.ManyToManyField(Reply)

    def __str__(self):
        return self.title

我希望做的其中一件事是获取某个评论的所有评分,并计算这些数字的平均值。我试图这样做:

class Reply(models.Model):
    rating = models.DecimalField(decimal_places=1, 
                                 max_digits = 2,
                                 validators = [MaxValueValidator(5), MinValueValidator(0)],
                                 default = 0
                                )
    text_reply = models.TextField(max_length = 200)

回溯

def calculate_average():
    objects = Review.objects.all()
    average = 0
    length = 0
    for reply in objects:
        average += reply.replies.rating
        length += 1
    return average/length

1 个答案:

答案 0 :(得分:1)

用于计算特定评论的评分,

result = {}
objects = Review.objects.all()
for review in objects:
    average = 0
    length = 0
    for reply in review​.replies.all():
        average += reply.rating
        length += 1
    average /= length
    result.update({review.title, average})

如果您正在寻找模型属性来计算单个模型的相同属性,那么

class Review(models.Model):

    def calculate_rating(self):
        average = 0
        length = 0
        for reply in self​.replies.all():
            average += reply.rating
            length += 1
        if average:
            average /= length
        return average