通过计算和减去Django中的外键实例来计算得分

时间:2015-08-02 17:39:46

标签: django django-models

我有一个课程摘要:

class Summary(models.Model):
    title = models.CharField(max_length=128)
    category = models.ForeignKey(Category)
    subcategory = models.ForeignKey(Subcategory)
    content = RichTextField(null=True, blank=True)
    users_rated_positive = models.ManyToManyField(
        User, blank=True, related_name='summaries_rated_positive')
    users_rated_negative = models.ManyToManyField(
        User, blank=True, related_name='summaries_rated_negative')
    author = models.ForeignKey(User, related_name='summaries_authored')

和一个类UserProfile:

class UserProfile(models.Model):
    user = models.OneToOneField(User, primary_key=True, related_name='profile')
    karma = models.IntegerField(default=0)
    rank = models.IntegerField(null=True,blank=True)

我希望将业力计算为所有用户摘要的正评分减去所有用户摘要的负评级

我想我可以添加这样的属性而不是字段:

@property
def karma(self):
summaries_list = self.user.summaries_authored.all()
positive_karma = sum(
    [summary.users_rated_positive.count() for summary in summaries_list])
negative_karma = sum(
    [summary.users_rated_negative.count() for summary in summaries_list])
return positive_karma - negative_karma

这是正确的方法吗?我觉得我应该使用聚合或注释,但说实话,我是Django的新手,并不完全确定它们如何适用于复杂情况。

1 个答案:

答案 0 :(得分:1)

from django.db.models import Count  

positive_karma = Summary.objects.filter(author=self.user).aggregate(pos_count=Count('users_rated_positive'))['pos_count']

negative_karma = Summary.objects.filter(author=self.user).aggregate(neg_count=Count('users_rated_negative'))['neg_count']

aggregate返回一个字典,因此必须通过键

检索实际值

如果你想获得每个用户的pos / neg评分,你可以使用annotate