如何在Django视图中根据外键过滤模型数据?

时间:2016-02-26 19:09:43

标签: python django filter models

我有两个模型,User和UserRating,通过一对多关系连接如何过滤特定用户的评级,以便我可以计算他的整体评分并在他的个人资料中显示。谢谢。

#this is model for user
class User(models.Model):
    username = models.CharField(max_length=128, unique=True)
    email = models.EmailField(max_length=128, unique=True)
    #password = forms.CharField(max_length=32, widget=forms.PasswordInput)
    profilepic = models.ImageField(null=True)
    firstname = models.CharField(max_length=128, null=True)
    secondname = models.CharField(max_length=128, null=True)
    city = models.ForeignKey(City)


#this is the model for user ratings - one to many relationship with User
class UserRating(models.Model):
    user = models.ForeignKey(User)
    comment = models.CharField(max_length=500)
    rating = models.IntegerField(default=5)

2 个答案:

答案 0 :(得分:2)

如果您有User个对象,则可以reverse relationship访问所有评分:

user.userrating_set.all()

要计算他的平均评分,请使用Aggregation

from django.db.models import Avg
user.userrating_set.all().aggregate(Avg('rating'))

修改

如果您希望将此作为用户模型的属性,请执行以下操作:

class User(models.Model):
    username = models.CharField(max_length=128, unique=True)
    ... 

    @property
    def avg_rating(self):
        return self.userrating_set.all().aggregate(Avg('rating'))

然后您可以使用

访问它
user.avg_rating

答案 1 :(得分:1)

编辑 - 已更新,因此您可以按评分数除以

在视图中......

from django.db.models import Sum

current_user_rating_object = UserRating.objects.filter(user=request.user)
ratings = current_user_rating_objects.count()
total_rating = current_user_rating_object.aggregate(Sum(total_rating=Sum('rating', distinct=True))['total_rating']
weighted_rating = total_rating / ratings