本文整理汇总了Python中django.db.models.Avg方法的典型用法代码示例。如果您正苦于以下问题:Python models.Avg方法的具体用法?Python models.Avg怎么用?Python models.Avg使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models
的用法示例。
在下文中一共展示了models.Avg方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: resolve_clubAttendance
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Avg [as 别名]
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
示例2: update_teams_score
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Avg [as 别名]
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()
示例3: get
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Avg [as 别名]
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
示例4: recs_using_association_rules
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Avg [as 别名]
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])))
示例5: get_context_data
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Avg [as 别名]
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.
示例6: get_item_report
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Avg [as 别名]
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
示例7: handle
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Avg [as 别名]
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
示例8: get_course_average_progress_for_time_period
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Avg [as 别名]
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
示例9: get_course_average_days_to_complete_for_time_period
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Avg [as 别名]
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
示例10: index
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Avg [as 别名]
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}
)
示例11: update
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Avg [as 别名]
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']
示例12: create
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Avg [as 别名]
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']
示例13: average_amount
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Avg [as 别名]
def average_amount(self):
return Split.objects.personal().recurrence(self.id).aggregate(
models.Avg('amount'))['amount__avg']
示例14: statistics
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Avg [as 别名]
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)
示例15: get_context_data
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Avg [as 别名]
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)