简体   繁体   English

Django汇总:两个不在同一模型中的字段的相加和

[英]Django Aggregation: Sum of Multiplication of two fields that are not in same model

I have three models (Django 1.6.5): 我有三个模型(Django 1.6.5):

class Vote(models.Model):
    voter  = models.ForeignKey(UserSettings)
    answer = models.ForeignKey(Answer)
    rating = models.IntegerField()

class Answer(models.Model):
    content = models.CharField(max_length=255)

class UserSettings(models.Model): 
    user = models.OneToOneField(User, related_name='settings')
    weight = models.FloatField(default=1.0)

Basically, a user (voter) can vote for an answer by giving a rating. 基本上,用户(投票者)可以通过给出评分来为答案投票。 I know how to sum the ratings by answer: 我知道如何通过回答来汇总评分:

Vote.objects.all().values('answer').annotate(score=Sum('rating'))

The only subtlety is that each voter has a weight (all voters are not equal!) and I want to sum each product rating*weight. 唯一的微妙之处在于,每个选民都有权重(所有选民都不相等!),我想对每个产品评分*权重求和。 I know (from here ) that something like that can be done: 我知道(从这里开始 )可以做类似的事情:

Sum('id',field="field1*field2")

and it would work well if my 2 fields are in the same model but it doesn't work if they are not. 如果我的2个字段位于同一模型中,则效果很好,但如果两个字段不在同一模型中,则效果不佳。 In other words, command: 换句话说,命令:

Vote.objects.all().values('answer').annotate(score=Sum('id',field="rating*voter__weight"))

does not work. 不起作用。 Any help greatly appreciated! 任何帮助,不胜感激!

The problem is that we need the join with another table (in this case UserSettings), so we need "force" the join. 问题在于我们需要与另一个表(在本例中为UserSettings)进行联接,因此我们需要“强制”联接。

q = Vote.objects.all().filter(voter__settings__weight__gt=0).values("answer").annotate(Sum('id', field='rating*weight'))

To force the join I used the filter clause (In fact I suppose that all the users have a weight greater than 0) but is just used to force the join. 为了强制连接,我使用了filter子句(实际上,我假设所有用户的权重都大于0),但仅用于强制连接。 Then you can use the weight field. 然后,您可以使用体重字段。

PD: I think that this problem is solved in the latest version of Django with Conditional Expressions: https://docs.djangoproject.com/es/1.10/ref/models/conditional-expressions/ PD:我认为此问题已在最新版本的Django中通过条件表达式解决: https : //docs.djangoproject.com/es/1.10/ref/models/conditional-expressions/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM