Python django.db.models.Avg() Examples

The following are 30 code examples for showing how to use django.db.models.Avg(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models , or try the search function .

Example 1
Project: Politikon   Author: KlubJagiellonski   File: tasks.py    License: GNU General Public License v2.0 6 votes vote down vote up
def update_teams_score():
    """
    Update teams score
    """
    logger.debug("'accounts:tasks:update_teams_score' worker up")

    for team in Team.objects.all():
        team.avg_reputation = UserProfile.objects.filter(team=team).\
            aggregate(Avg('reputation'))['reputation__avg']
        team.avg_total_cash = UserProfile.objects.filter(team=team).\
            aggregate(Avg('total_cash'))['total_cash__avg']
        team.avg_portfolio_value = UserProfile.objects.filter(team=team).\
            aggregate(Avg('portfolio_value'))['portfolio_value__avg']
        team.avg_weekly_result = UserProfile.objects.filter(team=team).\
            aggregate(Avg('weekly_result'))['weekly_result__avg']
        team.avg_monthly_result = UserProfile.objects.filter(team=team).\
            aggregate(Avg('monthly_result'))['monthly_result__avg']
        team.save() 
Example 2
Project: cms   Author: amfoss   File: log.py    License: GNU General Public License v3.0 6 votes vote down vote up
def resolve_clubAttendance(self, info, **kwargs):
        start = kwargs.get('startDate')
        end = kwargs.get('endDate')
        logs = Log.objects.all()
        if start is not None:
            logs = logs.filter(date__gte=start)
        else:
            raise Exception('Start date required')
        if end is not None:
            logs = logs.filter(date__lte=end)
        else:
            end = date.today()
        data = {
            'logs': logs,
            'avgDuration': logs.aggregate(Avg('duration')),
            'start': start,
            'end': end
        }
        return data 
Example 3
Project: lexpredict-contraxsuite   Author: LexPredict   File: models.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get(cls, as_dataframe: bool = True, **filter_kwargs):
        """
        Return grouped by method/name statistic with AVG time and N calls
        :param as_dataframe: bool - whether return pandas.dataframe or plain QuerySet
        :param filter_kwargs: positional arguments represents options for filter() qs method
        :return: pandas Dataframe OR QuerySet
        """
        # .filter(has_error=False)\
        qs = cls.objects\
            .values('method', 'path', 'name')\
            .annotate(calls=Count('id'),
                      errors=Count(Case(
                          When(has_error=True, then=1),
                          output_field=IntegerField(),
                      )),
                      avg_time=Avg('time'), max_time=Max('time'))\
            .filter(**filter_kwargs)
        qs = list(qs)
        qs.sort(key=lambda m: -m['calls'])
        if as_dataframe:
            return pd.DataFrame.from_records(qs, columns=['name', 'method',
                                                          'calls', 'errors',
                                                          'avg_time', 'max_time'])
        return qs 
Example 4
Project: moviegeek   Author: practical-recommender-systems   File: views.py    License: MIT License 6 votes vote down vote up
def recs_using_association_rules(request, user_id, take=6):
    events = Log.objects.filter(user_id=user_id)\
                        .order_by('created')\
                        .values_list('content_id', flat=True)\
                        .distinct()

    seeds = set(events[:20])

    rules = SeededRecs.objects.filter(source__in=seeds) \
        .exclude(target__in=seeds) \
        .values('target') \
        .annotate(confidence=Avg('confidence')) \
        .order_by('-confidence')

    recs = [{'id': '{0:07d}'.format(int(rule['target'])),
             'confidence': rule['confidence']} for rule in rules]

    print("recs from association rules: \n{}".format(recs[:take]))
    return JsonResponse(dict(data=list(recs[:take]))) 
Example 5
Project: django-marketplace   Author: klingj3   File: views.py    License: MIT License 6 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        user = SocialProfile.objects.get(slug=self.kwargs['slug']).owner
        context['posts_list'] = Post.objects.filter(owner=user).order_by("-modified")
        context['reviews_list'] = Review.objects.filter(reviewee=user).order_by("-modified")
        if len(context['reviews_list']) > 0:
            average = context['reviews_list'].aggregate(Avg('score'))['score__avg']
        else:
            average = 0
        average_str = []
        val = 0.00
        while val < 5:
            if val + 1 <= average:
                average_str.append('f')
            elif val + 0.5 <= average:
                average_str.append('h')
            else:
                average_str.append('e')
            val += 1
        context['average_str'] = average_str
        context['average'] = average
        return context

# Update a profile. 
Example 6
Project: swarfarm   Author: PeteAndersen   File: generate.py    License: Apache License 2.0 6 votes vote down vote up
def get_item_report(qs, total_log_count, **kwargs):
    if qs.count() == 0:
        return None

    min_count = kwargs.get('min_count', max(1, int(MINIMUM_THRESHOLD * total_log_count)))

    results = list(
        qs.values(
            'item',
            name=F('item__name'),
            icon=F('item__icon'),
        ).annotate(
            count=Count('pk'),
            min=Min('quantity'),
            max=Max('quantity'),
            avg=Avg('quantity'),
            drop_chance=Cast(Count('pk'), FloatField()) / total_log_count * 100,
            qty_per_100=Cast(Sum('quantity'), FloatField()) / total_log_count * 100,
        ).filter(count__gt=min_count).order_by('-count')
    )

    return results 
Example 7
Project: canvas   Author: canvasnetworks   File: average_following.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def handle(self, *args, **options):
        cutoff_date = datetime.date.today() - datetime.timedelta(days=(30 * MONTHS))
        counts = User.objects.filter(date_joined__gt=cutoff_date)
        counts = counts.annotate(follow_count=Count('following')).order_by('follow_count')

        avg = counts.aggregate(Avg('follow_count'))['follow_count__avg']

        print
        print 'Following counts for users who signed up in the last {} months'.format(MONTHS)
        print '----------------'
        print 'Average: {:.3} per user'.format(avg)

        try:
            std_dev = counts.aggregate(StdDev('follow_count'))['follow_count__stddev']
            print 'StdDev:  {:.3}'.format(std_dev)
        except DatabaseError:
            print "(can't get standard deviation with SQLite)"
        counts = counts.values_list('follow_count', flat=True)
        print 'Median: {}'.format(percentile(counts, 0.5))
        print 
Example 8
Project: figures   Author: appsembler   File: metrics.py    License: MIT License 5 votes vote down vote up
def get_course_average_progress_for_time_period(site, start_date, end_date, course_id):
    filter_args = dict(
        site=site,
        date_for__gt=prev_day(start_date),
        date_for__lt=next_day(end_date),
        course_id=course_id
    )

    qs = CourseDailyMetrics.objects.filter(**filter_args)
    if qs:
        value = qs.aggregate(average=Avg('average_progress'))['average']
        return float(Decimal(value).quantize(Decimal('.00')))
    else:
        return 0.0 
Example 9
Project: figures   Author: appsembler   File: metrics.py    License: MIT License 5 votes vote down vote up
def get_course_average_days_to_complete_for_time_period(site, start_date, end_date, course_id):
    filter_args = dict(
        site=site,
        date_for__gt=prev_day(start_date),
        date_for__lt=next_day(end_date),
        course_id=course_id
    )

    qs = CourseDailyMetrics.objects.filter(**filter_args)
    if qs:
        return int(math.ceil(
            qs.aggregate(average=Avg('average_days_to_complete'))['average']
        ))
    else:
        return 0 
Example 10
Project: donation-tracker   Author: GamesDoneQuick   File: public.py    License: Apache License 2.0 5 votes vote down vote up
def index(request, event=None):
    event = viewutil.get_event(event)
    eventParams = {}

    if event.id:
        eventParams['event'] = event.id

    agg = Donation.objects.filter(
        transactionstate='COMPLETED', testdonation=False, **eventParams
    ).aggregate(
        amount=Cast(Coalesce(Sum('amount'), 0), output_field=FloatField()),
        count=Count('amount'),
        max=Cast(Coalesce(Max('amount'), 0), output_field=FloatField()),
        avg=Cast(Coalesce(Avg('amount'), 0), output_field=FloatField()),
    )
    agg['target'] = float(event.targetamount)
    count = {
        'runs': filters.run_model_query('run', eventParams).count(),
        'prizes': filters.run_model_query('prize', eventParams).count(),
        'bids': filters.run_model_query('bid', eventParams).count(),
        'donors': filters.run_model_query('donorcache', eventParams)
        .values('donor')
        .distinct()
        .count(),
    }

    if 'json' in request.GET:
        return HttpResponse(
            json.dumps({'count': count, 'agg': agg}, ensure_ascii=False,),
            content_type='application/json;charset=utf-8',
        )

    return views_common.tracker_response(
        request, 'tracker/index.html', {'agg': agg, 'count': count, 'event': event}
    ) 
Example 11
Project: donation-tracker   Author: GamesDoneQuick   File: donation.py    License: Apache License 2.0 5 votes vote down vote up
def update(self):
        aggregate = Donation.objects.filter(
            donor=self.donor, transactionstate='COMPLETED'
        )
        if self.event:
            aggregate = aggregate.filter(event=self.event)
        aggregate = aggregate.aggregate(
            total=Coalesce(Sum('amount'), 0.0),
            count=Coalesce(Count('amount'), 0),
            max=Coalesce(Max('amount'), 0.0),
            avg=Coalesce(Avg('amount'), 0.0),
        )
        self.donation_total = aggregate['total']
        self.donation_count = aggregate['count']
        self.donation_max = aggregate['max']
        self.donation_avg = aggregate['avg'] 
Example 12
Project: cride-platzi   Author: pablotrinidad   File: ratings.py    License: MIT License 5 votes vote down vote up
def create(self, data):
        """Create rating."""
        offered_by = self.context['ride'].offered_by

        Rating.objects.create(
            circle=self.context['circle'],
            ride=self.context['ride'],
            rating_user=self.context['request'].user,
            rated_user=offered_by,
            **data
        )

        ride_avg = round(
            Rating.objects.filter(
                circle=self.context['circle'],
                ride=self.context['ride']
            ).aggregate(Avg('rating'))['rating__avg'],
            1
        )
        self.context['ride'].rating = ride_avg
        self.context['ride'].save()

        user_avg = round(
            Rating.objects.filter(
                rated_user=offered_by
            ).aggregate(Avg('rating'))['rating__avg'],
            1
        )
        offered_by.profile.reputation = user_avg
        offered_by.profile.save()

        return self.context['ride'] 
Example 13
Project: silverstrike   Author: agstrike   File: models.py    License: MIT License 5 votes vote down vote up
def average_amount(self):
        return Split.objects.personal().recurrence(self.id).aggregate(
            models.Avg('amount'))['amount__avg'] 
Example 14
Project: karrot-backend   Author: yunity   File: api.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def statistics(self, request, pk=None):
        instance = self.get_object()
        weight = instance.activities.annotate(
            feedback_weight=Case(
                When(feedback_as_sum=True, then=Sum('feedback__weight')),
                default=Avg('feedback__weight'),
                output_field=FloatField()
            )
        ).aggregate(result_weight=Sum('feedback_weight'))['result_weight']
        data = {
            'feedback_count': instance.feedback_count,
            'feedback_weight': round(weight or 0),
            'activities_done': instance.activities_done,
        }
        return Response(data) 
Example 15
Project: django-multiple-user-types-example   Author: sibtc   File: teachers.py    License: MIT License 5 votes vote down vote up
def get_context_data(self, **kwargs):
        quiz = self.get_object()
        taken_quizzes = quiz.taken_quizzes.select_related('student__user').order_by('-date')
        total_taken_quizzes = taken_quizzes.count()
        quiz_score = quiz.taken_quizzes.aggregate(average_score=Avg('score'))
        extra_context = {
            'taken_quizzes': taken_quizzes,
            'total_taken_quizzes': total_taken_quizzes,
            'quiz_score': quiz_score
        }
        kwargs.update(extra_context)
        return super().get_context_data(**kwargs) 
Example 16
Project: opensurfaces   Author: seanbell   File: utils.py    License: MIT License 5 votes vote down vote up
def all_aggregations(queryset, key):
    """ Performs all available aggregations on a queryset """
    return queryset.filter(**{key + '__isnull': False}).aggregate(
        min=Min(key),
        avg=Avg(key),
        max=Max(key),
        std=StdDev(key),
        count=Count(key),
        sum=Sum(key),
    ) 
Example 17
Project: SEMS   Author: urankajtazaj   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def student_detail(request, pk):
    student = Student.objects.get(pk=pk)
    success = Grade.objects.filter(student=student.user).order_by('-grade')
    details = Grade.objects.filter(student=student.user, grade__gt=4).aggregate(Avg('grade'), Max('grade'), Min('grade'))

    if request.user.is_authenticated:
        return render(
            request, 'student_profile.html', {'student': student, 'success': success, 'details': details},
        )
    else:
        return redirect('login')


# ######################################################## 
Example 18
Project: cms   Author: amfoss   File: log.py    License: GNU General Public License v3.0 5 votes vote down vote up
def resolve_avgDuration(self, info):
        return self['log'].aggregate(Avg('duration'))['duration__avg'] 
Example 19
Project: cms   Author: amfoss   File: log.py    License: GNU General Public License v3.0 5 votes vote down vote up
def resolve_memberStats(self, info, **kwargs):
        order = kwargs.get('order')
        if order is None:
            order = '-presentCount'
        return self['logs'].values('member').annotate(
            presentCount=Count('member'),
            avgDuration=Avg('duration'),
            totalDuration=Sum('duration')).order_by(order, '-presentCount', '-totalDuration') 
Example 20
Project: cms   Author: amfoss   File: schema.py    License: GNU General Public License v3.0 5 votes vote down vote up
def resolve_attendance(self, info, **kwargs):
        logs = Log.objects.filter(member__username=self['username'])
        start = kwargs.get('startDate')
        end = kwargs.get('endDate')
        if start is not None:
            logs = logs.filter(date__gte=start)
        if end is not None:
            logs = logs.filter(date__lte=end)
        data = {'logs': logs.values(), 'avgDuration': logs.aggregate(Avg('duration'))}
        return data 
Example 21
Project: django-mock-queries   Author: stphivos   File: test_query.py    License: MIT License 5 votes vote down vote up
def test_query_aggregate_on_related_field(self):
        with mocked_relations(Manufacturer):
            cars = [Car(speed=1), Car(speed=2), Car(speed=3)]

            make = Manufacturer()
            make.car_set = MockSet(*cars)

            self.mock_set.add(make)

            result = self.mock_set.aggregate(Avg('car__speed'))
            assert result['car__speed__avg'] == sum([c.speed for c in cars]) / len(cars) 
Example 22
Project: wagtail   Author: wagtail   File: backend.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _refresh_title_norms(self):
        """
        Refreshes the value of the title_norm field.

        This needs to be set to 'lavg/ld' where:
         - lavg is the average length of titles in all documents (also in terms)
         - ld is the length of the title field in this document (in terms)
        """

        lavg = self.entries.annotate(title_length=Length('title')).aggregate(Avg('title_length'))['title_length__avg']
        self.entries.annotate(title_length=Length('title')).filter(title_length__gt=0).update(title_norm=lavg / F('title_length')) 
Example 23
Project: mrs   Author: betagouv   File: models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def validation_average_delay(self):
        return self.mrsrequest_set.status_changed(
            'validated',
            self.date,
        ).aggregate(result=models.Avg('delay'))['result'] 
Example 24
Project: mrs   Author: betagouv   File: crudlfap.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_validation_average_delay(self):
        return self.object_list.aggregate(
            result=models.Avg('validation_average_delay')
        )['result'] 
Example 25
Project: mrs   Author: betagouv   File: crudlfap.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_average_payment_delay(self):
        mrsrequests = self.mrsrequests.created(
            **{
                k: v
                for k, v in self.filterset.form.cleaned_data.items()
                if k.startswith('date_')
            },
            caisse=self.filterset.form.cleaned_data.get('caisse')
        )
        return '{:0.2f}'.format(
            mrsrequests.aggregate(
                result=models.Avg('delay')
            )['result'] or 0
        ).replace('.', ',') 
Example 26
Project: mrs   Author: betagouv   File: views.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def average_payment_delay(self):
        return '{:0.2f}'.format(
            MRSRequest.objects.aggregate(
                result=models.Avg('delay')
            )['result'] or 0
        ) 
Example 27
Project: django-pivot   Author: martsberger   File: test.py    License: MIT License 5 votes vote down vote up
def test_pivot_aggregate(self):
        shirt_sales = ShirtSales.objects.all()

        data = ExpressionWrapper(F('units') * F('price'), output_field=DecimalField())
        pt = pivot(ShirtSales, 'store__region__name', 'shipped', data, Avg, default=0)

        for row in pt:
            region_name = row['store__region__name']
            for dt in (key for key in row.keys() if key != 'store__region__name'):
                spends = [ss.units * ss.price for ss in shirt_sales if force_text(ss.shipped) == force_text(dt) and ss.store.region.name == region_name]
                avg = sum(spends) / len(spends) if spends else 0
                self.assertAlmostEqual(row[dt], float(avg), places=4) 
Example 28
Project: protwis   Author: protwis   File: distances.py    License: Apache License 2.0 5 votes vote down vote up
def fetch_and_calculate(self, with_arr = False):
        ## REQUIRES PSQL SETTINGS TO HAVE MORE MEMORY
        # sudo nano /etc/postgresql/9.3/main/postgresql.conf
        # shared_buffers = 2GB
        # work_mem = 100MB
        # temp_buffers = 500MB
        # sudo /etc/init.d/postgresql restart
        ds_with_key = {}
        if with_arr:
            ds = list(Distance.objects.filter(structure__in=self.structures).exclude(gns_pair__contains='8x').exclude(gns_pair__contains='12x').exclude(gns_pair__contains='23x').exclude(gns_pair__contains='34x').exclude(gns_pair__contains='45x') \
                            .values('gns_pair') \
                            .annotate(mean = Avg('distance'), std = StdDev('distance'), c = Count('distance'), dis = Count('distance'),arr=ArrayAgg('distance'),arr2=ArrayAgg('structure__pdb_code__index'),arr3=ArrayAgg('gns_pair')).values_list('gns_pair','mean','std','c','dis','arr','arr2','arr3').filter(c__gte=int(0.8*len(self.structures))))
            for i,d in enumerate(ds):
                ds[i] = list(ds[i])
                ds[i][3] = d[2]/d[1]
                ds_with_key[d[0]] = ds[i]
        else:
            ds = list(Distance.objects.filter(structure__in=self.structures).exclude(gns_pair__contains='8x').exclude(gns_pair__contains='12x').exclude(gns_pair__contains='23x').exclude(gns_pair__contains='34x').exclude(gns_pair__contains='45x') \
                            .values('gns_pair') \
                            .annotate(mean = Avg('distance'), std = StdDev('distance'), c = Count('distance')).values_list('gns_pair','mean','std','c').filter(c__gte=int(len(self.structures)*0.8)))
            for i,d in enumerate(ds):
                ds[i] += (d[2]/d[1],)
                ds_with_key[d[0]] = ds[i]
        # # print(ds.query)
        # print(ds[1])
        # Assume that dispersion is always 4
        if len(self.structures)>1:
            stats_sorted = sorted(ds, key=lambda k: -k[3])
        else:
            stats_sorted = sorted(ds, key=lambda k: -k[1])
        #print(ds[1])

        self.stats_key = ds_with_key
        self.stats = stats_sorted 
Example 29
Project: PonyConf   Author: PonyConf   File: models.py    License: Apache License 2.0 5 votes vote down vote up
def get_queryset(self):
        qs = super().get_queryset()
        qs = qs.annotate(score=Coalesce(Avg('vote__vote'), 0))
        return qs 
Example 30
Project: registration   Author: HackAssistant   File: models.py    License: MIT License 5 votes vote down vote up
def annotate_vote(cls, qs):
        return qs.annotate(vote_avg=Avg('vote__calculated_vote'))