Django request, average counter

I have a model Donationdefined as:

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

Each user can donate several times to any project, so in db I can have the following:

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

Now I need to calculate the average value of a separate project for each user, in this case it will be:

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

So far, I have been as follows:

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

This gives me a list of pairs of project/ pairs userthat I can work with in python.

I would like to know if there is a way query-onlyfor this?

My setup:

  • Django 1.8
  • PostgreSQL
+4
source share
1 answer

, . , 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: QuerySet

, , :

from django.db.models import Count, Avg

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

: 1.8

+4

Source: https://habr.com/ru/post/1651687/


All Articles