简体   繁体   English

Django查询,平均数不同

[英]Django query, average count distinct

I have a Donation model defined as: 我的Donation模型定义为:

Donation
    project = models.ForeignKey(Project)
    user = models.CharField()

Each user can donate multiple time to any project, so in db I can have the following: 每个用户可以多次捐赠给任何项目,因此在db中我可以拥有以下内容:

 Donation
-------------------
 project | user
-------------------
 1       |  A
 2       |  A
 3       |  A
 1       |  B
 2       |  B
 2       |  C

Now, I need to compute the average of distinct project per user, in this case it would be: 现在,我需要计算每个用户的不同项目的平均值,在这种情况下它将是:

A: 3
B: 2
C: 1
=> ( 3 + 2 + 1 ) / 3 = 2

What I have so far is the following: 到目前为止我所拥有的是以下内容:

distinct_pairs = Donation.objects.order_by('project')
         .values('user', 'project')
         .distinct()

This gives me a list of distincts project / user pairs, that I can work with in python. 这给了我一个区别project / user对的列表,我可以在python中使用它。

I would like to know if there is a query-only way to do this? 我想知道是否有query-only方法来做到这一点?

My setup: 我的设置:

  • Django 1.8 Django 1.8
  • PostgreSQL PostgreSQL的

You don't need to sum values for average, you can just count distinct values and divide by number of distinct users. 您不需要对平均值求和,您可以只计算不同的值并除以不同用户的数量。 Also order_by is redundant since we need only counts. order_by也是多余的,因为我们只需要计数。

distinct_pairs_count = Donation.objects.values('user', 'project').distinct().count()

distinct_users_count = Donation.objects.values('user').distinct().count()

average = distinct_pairs_count / float(distinct_users_count)  # in Python 2
average = distinct_pairs_count / distinct_users_count         # in Python 3

EDIT: make it one QuerySet 编辑:使它成为一个QuerySet

I think you can achieve this by one query but I can't check it right now: 我想你可以通过一个查询来实现这一点,但我现在无法检查它:

from django.db.models import Count, Avg

average = Donation.objects.values('user', 'project')
             .annotate(num_projects=Count('project', distinct=True))
             .aggregate(Avg('num_projects'))

See: aggregating annotations in 1.8 请参阅: 1.8中的聚合注释

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

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