我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.db.models.Avg()。
def getRegistrationTypesAveragesByYear(): srs = EventRegistration.objects.all() eligible_years = [x['event__year'] for x in srs.values('event__year').annotate(Count('event__year'))] eligible_years.sort() year_averages = [] for year in eligible_years: this_year_results = srs.filter(event__year=year).annotate( student=Case(When(registration__student=True,then=100),default=0,output_field=IntegerField()), door=Case(When(registration__payAtDoor=False,then=100),default=0,output_field=IntegerField()), droppedIn=Case(When(dropIn=True,then=100),default=0,output_field=IntegerField()), cancellation=Case(When(cancelled=True,then=100),default=0,output_field=IntegerField()), ).aggregate(Student=Avg('student'),Door=Avg('door'),DropIn=Avg('droppedIn'),Cancelled=Avg('cancellation'),year=Min('event__year')) year_averages.append(this_year_results) return year_averages
def sort_by_estimation(user, category): """ Sorts books by average count of estimation of each book. Uses aggregate function. :param django.contrib.auth.models.User user: The request user. :param app.models.Category category: The category. :return: The list with sorted books. """ books = [] filtered_books = Book.exclude_private_books(user, Book.objects.filter(id_category=category)) for item in filtered_books: book_rating = BookRating.objects.filter(id_book=item).aggregate(Avg('rating')) book = {'id': item.id, 'name': item.book_name, 'author': item.id_author.author_name, 'url': item.photo.url if item.photo else '', 'rating': book_rating['rating__avg']} books.append(book) return sorted(books, key=lambda info: (info['rating'] is not None, info['rating']), reverse=True) # ------------------------------------------------------------------------------------------------------------------
def get_queryset(self): """Get queryset.""" return self.model.objects.all() \ .only('id', 'salutation', 'name', 'email') \ .annotate( number_of_books=Count('books'), first_book_published_on=Min('books__publication_date'), last_book_published_on=Max('books__publication_date'), lowest_book_price=Min('books__price'), highest_book_price=Max('books__price'), average_book_price=Avg('books__price'), average_number_of_pages_per_book=Avg('books__pages'), number_of_books_sold=Count('books__order_lines'), total_amount_earned=Sum( 'books__order_lines__book__price' ) )
def _lecturas_del_periodo(anio, mes, quincena=None, region_id=None, funcion=Avg): muestras = Muestra.objects.filter(anio=anio, mes=mes, aprobada=True) if quincena: muestras = muestras.filter(quincena=quincena) lecturas = Lectura.objects.filter(muestra__in=muestras, precio__gt=0) if region_id: lecturas = lecturas.filter( muestra__planilla_de_relevamiento__zona__jurisdiccion__region__pk=region_id) lecturas = lecturas.annotate(orden=F("producto_con_marca__producto_generico__id"))\ .annotate(producto=F("producto_con_marca__producto_generico__nombre"))\ .annotate(comercio=F('muestra__planilla_de_relevamiento__comercio__nombre'))\ .values('comercio', 'producto')\ .annotate(valor=funcion('precio'))\ .annotate(c_p=Concat(F('muestra__planilla_de_relevamiento__comercio__nombre'), F("producto_con_marca__producto_generico__nombre")))\ .order_by('orden', 'comercio') return lecturas
def change_rating(request): if request.is_ajax(): rating_form = ChangeRatingForm(request.POST) if rating_form.is_valid(): with transaction.atomic(): set_rating(request, rating_form) book_rating = BookRating.objects.filter(id_book=Book.objects.get(id=rating_form.cleaned_data['book'])) data = {'avg_rating': round(book_rating.aggregate(Avg('rating'))['rating__avg'], 1), 'rating_count': '({})'.format(book_rating.count())} return HttpResponse(json.dumps(data), content_type='application/json') else: return HttpResponse(status=404) # ----------------------------------------------------------------------------------------------------------------------
def detail_assignmentype(request, pk): """ Dashboard of an assignmentype (id=pk) """ prof = request.user.prof context = {'prof': prof} assignmentype = Assignmentype.objects.filter(pk=pk, prof=prof).first() assignments = assignmentype.assignment_set.\ annotate(std=StdDev('evalassignment__grade_assignment'), mean=Avg('evalassignment__grade_assignment')) if assignmentype: context['assignmentype'] = assignmentype context['assignments'] = assignments context['range_grades'] = range(assignmentype.nb_grading) return render(request, 'gradapp/detail_assignmentype.html', context) else: return redirect('gradapp:list_assignmentypes_running')
def LocationPerformanceCSV(request): # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="locationPerformance.csv"' startDate = getDateTimeFromGet(request,'startDate') endDate = getDateTimeFromGet(request,'endDate') results = getLocationPerformance(startDate,endDate) writer = csv.writer(response) # Note: These are not translated because the chart Javascript looks for these keys writer.writerow(['Location','# Series','# Students','Avg. Students/Series']) for location,data in results.items(): writer.writerow([ location, # The location name data.get('series',0), # The num. of series taught there data.get('registrations',0), # The num. of students taught there float(data.get('registrations',0)) / data.get('series',1) ]) return response
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])))
def get_context_data(self, **kwargs): context = super(DepartmentDetailView, self).get_context_data(**kwargs) context['by_title_category'] = SalaryRecord.objects.filter(year=2015).filter(person__directory_record__department_obj=self.object).values('title_category').annotate(Avg('gross')).order_by('gross__avg').reverse() for d in context['by_title_category']: d['all__avg'] = SalaryRecord.objects.filter(year=2015).filter(title_category=d['title_category']).aggregate(Avg('gross'))['gross__avg'] context['by_year'] = [] for year in range(2006, 2016): year = str(year) avg = SalaryRecord.objects.filter(year=year).filter(person__directory_record__department_obj=self.object).aggregate(Avg('gross'))['gross__avg'] berkeley_avg = SalaryRecord.objects.filter(year=year).aggregate(Avg('gross'))['gross__avg'] context['by_year'].append({ 'year': year, 'avg': avg, 'berkeley_avg': berkeley_avg }) return context
def get_related_objects_selected_book(user, book_id, user_key=''): """ Returns the related objects of selected book :param app.models.TheUser user: The request for selecting book. :param int book_id: The ID of selected book. :param str user_key: The key which is used to get user if it's an API call. :return: Related objects. """ book = Book.objects.get(id=book_id) book_rating = BookRating.objects.filter(id_book=book) try: if not user.is_anonymous: added_book = AddedBook.objects.get(id_user=TheUser.objects.get(id_user=user), id_book=book) else: the_user = TheUser.objects.get(auth_token=user_key) added_book = AddedBook.objects.get(id_user=the_user, id_book=book) except ObjectDoesNotExist: added_book = None comments = BookComment.objects.filter(id_book=Book.objects.get(id=book_id)).order_by('-id') return {'book': book, 'avg_book_rating': book_rating.aggregate(Avg('rating')), 'book_rating_count': book_rating.count(), 'added_book': added_book, 'comments': comments} # ------------------------------------------------------------------------------------------------------------------
def change_rating(request): user = get_object_or_404(TheUser, auth_token=request.data.get('user_token')) book = get_object_or_404(Book, id=request.data.get('book_id')) rating = request.data.get('rating') if rating not in range(1, 11): return Response({}, status=404) book_ratings = BookRating.objects.filter(id_user=user, id_book=book) if book_ratings.exists(): book_rating = book_ratings[0] book_rating.rating = rating book_rating.save() else: BookRating.objects.create(id_user=user, id_book=book, rating=rating) logger.info("User '{}' set rating '{}' to book with id: '{}'.".format(user, rating, book.id)) return Response({'status': 200, 'detail': 'success', 'data': {'book_rating': round(book_ratings.aggregate(Avg('rating'))['rating__avg'], 1), 'book_rated_count': book_ratings.count()}}) # ----------------------------------------------------------------------------------------------------------------------
def get_queryset(self): """Get queryset.""" return self.model.objects.all() \ .annotate( number_of_books=Count('books'), first_book_published_on=Min('books__publication_date'), last_book_published_on=Max('books__publication_date'), lowest_book_price=Min('books__price'), highest_book_price=Max('books__price'), average_book_price=Avg('books__price'), average_number_of_pages_per_book=Avg('books__pages'), number_of_books_sold=Count('books__order_lines'), total_amount_earned=Sum('books__order_lines__book__price') ) \ .values('id', 'salutation', 'name', 'email', 'number_of_books', 'first_book_published_on', 'last_book_published_on', 'lowest_book_price', 'highest_book_price', 'average_book_price', 'average_number_of_pages_per_book', 'number_of_books_sold', 'total_amount_earned')
def get_grammar_avg(gid): grammar_avg = UserHistory.objects.filter(grammar=gid, complete=True).aggregate(Avg('score')) return round(grammar_avg["score__avg"],2)
def get_evaluation_avg_score(self, teacher: models.Teacher): # ?????? avg_score = models.Comment.objects.filter( timeslot__order__teacher=teacher, timeslot__order__status=models.Order.PAID, ).aggregate(Avg("score")) return avg_score["score__avg"] or 0
def average_for_views(self): case = Case(When(satisfied=True, then=Value(1)), When(satisfied=False, then=Value(0)), output_field=IntegerField()) return self.values('view_name').annotate(average=Avg(case), count=Count('view_name')).order_by('view_name')
def get_mean_price(self): return \ self.itinerary_set.all().annotate(min_price=Min('pricingoption__price')).aggregate(Avg('min_price'))[ 'min_price__avg']
def annotate_vote(cls, qs): return qs.annotate(vote_avg=Avg('vote__calculated_vote'))
def test_aggregation(self): AggregationNode.objects.create(price=100) node2 = AggregationNode.objects.create(price=200) AggregationNode.objects.create(price=300) self.assertEqual( AggregationNode.objects.all().aggregate(Avg('price'))['price__avg'], 200) self.assertEqual(list(AggregationNode.objects.filter( price=AggregationNode.objects.all().aggregate( Avg('price'))['price__avg'])), [node2])
def get_queryset(self): qs = super().get_queryset() qs = qs.annotate(score=Coalesce(Avg('vote__vote'), 0)) return qs
def request_dynamic(request): print('hello') if request.method == "POST": json_data = request.POST latitude = float(json_data["latitude"]) longitude = float(json_data["longitude"]) ROADS_API_URL = "https://roads.googleapis.com/v1/nearestRoads?points=" for i in range(51): radians = 3.14 * 0.02 * i x_latitude = float(latitude) + latitude_CONSTANT * cos(radians) y_longitude = float(longitude) + longitude_CONSTANT * sin(radians) ROADS_API_URL += str(x_latitude) + ',' + str(y_longitude) + '|' ROADS_API_URL = ROADS_API_URL[:(len(ROADS_API_URL) - 1)] ROADS_API_URL += '&key=AIzaSyCOhrN9Tbo_a1sxm9Kcy2zxb4C7b51XB1k' print(ROADS_API_URL) r = requests.get(ROADS_API_URL) json_response_data = json.loads(r.text) infos = json_response_data["snappedPoints"] a = {'roads': []} place_id_list = [] for id in infos: place_id_list.append(id["placeId"]) # place_id_set = set(place_id_list) w = TrafficModel.objects.values('place_id') w = w.annotate(total_avg_speed=Avg('avg_speed')) w = w.order_by('total_avg_speed') print(w) traffic_places_list = [] for member in w: if member["total_avg_speed"] <= 20.0: traffic_places_list.append(member) print(traffic_places_list) print(type(traffic_places_list)) for place in traffic_places_list: c = getplace_name_from_id(place["place_id"]) if(c is None): pass else: a["roads"].append(c) return json.dumps(a)
def get_rating(): return { 'count': RatingVote.objects.count(), 'avg': RatingVote.objects.aggregate(rating=Coalesce(models.Avg('rating'), 0))['rating'] }
def sentiment_view(request): today = datetime.datetime.now() period = datetime.datetime(today.year, today.month, 1) - datetime.timedelta(days=252) sentiments_obj = Post.objects.filter(date__gte=period) avg = sentiments_obj.aggregate(Avg('sentiment')) sentiments = [{"date": s["date"], "sentiment": (float(s["sentiment"] or 0.0) - avg["sentiment__avg"]) } for s \ in sentiments_obj.order_by('date').values('date', 'sentiment')] return render(request, '{}/sentiments.html'.format(settings.TEMPLATE_NAME), {'sentiments': sentiments})
def get_queryset(self, *args, **kwargs): overridden_reviews = Review.objects.filter(override_vote__isnull=False, submission_id=models.OuterRef('pk')) return self.request.event.submissions\ .order_by('review_id')\ .annotate(has_override=models.Exists(overridden_reviews))\ .annotate(avg_score=models.Case( models.When( has_override=True, then=self.request.event.settings.review_max_score + 1, ), default=models.Avg('reviews__score') ))\ .order_by('-state', '-avg_score')
def average_score(self): return self.reviews.all().aggregate(avg=models.Avg('score'))['avg']
def prepare_rating(self): ct = ContentType.objects.get_for_model(self) try: rating = OverallRating.objects.filter( object_id=self.pk, content_type=ct ).aggregate(r=Avg("rating"))["r"] return float(str(rating or "0")) except OverallRating.DoesNotExist: return 0.0
def prepare_rating(self, obj): ct = ContentType.objects.get_for_model(obj) try: rating = OverallRating.objects.filter( object_id=obj.pk, content_type=ct ).aggregate(r=Avg("rating"))["r"] return float(str(rating or "0")) except OverallRating.DoesNotExist: return 0.0
def get_stats(matches): return matches.aggregate( matches=Count('id', distinct=True), players=Count('matchplayer__player', distinct=True), mmr=Avg('matchplayer__player__dota_mmr'), )
def cloud_rate_view(request): days = [date.today() - timedelta(days=i) for i in range(1, 17)] rates = [Scene.objects.filter(date=day).aggregate(Avg('cloud_rate')).get('cloud_rate__avg') for day in days] data = zip(days, rates) return render(request, 'imagery/cloud_rate.html', {'cloud_rate_data': data})
def AveragesByClassTypeCSV(request): # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="averagesByClassDescriptionType.csv"' writer = csv.writer(response) startDate = getDateTimeFromGet(request,'startDate') endDate = getDateTimeFromGet(request,'endDate') results = getAveragesByClassType(startDate,endDate) role_names = [x.replace(str(_('Average ')),'') for x in results.keys() if x.startswith(str(_('Average ')))] header_list = [str(_('Class Type')),str(_('Total Classes')),str(_('Total Students')),str(_('Avg. Students/Class'))] for this_role in role_names: header_list += [str(_('Total %s' % this_role)), str(_('Avg. %s/Class' % this_role))] # Note: These are not translated because the chart Javascript looks for these keys writer.writerow(header_list) for key,value in results.items(): this_row = [ key, value.get(str(_('Series')),0), value.get(str(_('Registrations')),0), value.get(str(_('Average Registrations')),None), ] for this_role in role_names: this_row += [ value.get(str(_('Total %s' % this_role)), 0), value.get(str(_('Average %s' % this_role)), 0) ] writer.writerow(this_row) return response
def MonthlyPerformanceCSV(request): # Create the HttpResponse object with the appropriate CSV header. response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="monthlyPerformance.csv"' writer = csv.writer(response) yearTotals = getMonthlyPerformance() all_years = [k for k in yearTotals['Hours'].keys() if k != 'MonthlyAverage'] all_years.sort() # Write headers first headers_list = ['Data Series','Month','All-Time Avg.'] for year in all_years: headers_list.append(str(year)) writer.writerow(headers_list) # Note: These are not translated because the chart Javascript looks for these keys yearTotals_keys = { 'Total Student-Hours': 'StudentHours', 'Avg. Students/Hour': 'AvgStudents', 'Hours of Instruction': 'Hours', 'Unique Registrations': 'Registrations', 'Total Students': 'EventRegistrations', } for series,key in yearTotals_keys.items(): for month in range(1,13): this_row = [ series, month_name[month], yearTotals[key]['MonthlyAverage'][month], ] for year in all_years: this_row.append(yearTotals[key][year][month]) writer.writerow(this_row) return response
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)
def average_tickets_per_registration(): """ >>> SELECT AVG(registration.ticket) AS avg_ticket FROM registration """ avg_ticket = Registration.objects.aggregate(avg_ticket=Avg('ticket')) print(avg_ticket)
def prepare_overview_data_for_render(request): ## Chart sentiment scores of tweets try: worst_movie = Movie.objects.get(imdbID = Sentiment.objects.earliest('sentimentScore').imdbID) best_movie = Movie.objects.get(imdbID = Sentiment.objects.latest('sentimentScore').imdbID) except: worst_movie = best_movie = None try: worst_score = Sentiment.objects.earliest('sentimentScore') best_score = Sentiment.objects.latest('sentimentScore') except: best_score = worst_score = None num_tweets = Tweet.objects.count() num_movies = Movie.objects.count() try: avg_sentiment_num = Sentiment.objects.all().aggregate(Avg('sentimentScore'))['sentimentScore__avg'] avg_sentiment = str(round(avg_sentiment_num, 2)) except: avg_sentiment = avg_sentiment_num = None ## Prepare data to render on results page data_to_render = { 'worst_movie' : worst_movie, 'best_movie' : best_movie, 'num_tweets' : num_tweets, 'num_movies' : num_movies, 'avg_sentiment' : avg_sentiment, 'best_score' : best_score, 'worst_score' : worst_score, } return data_to_render ## ============================================================================= ## Create datasets for chart that displays the sentiment scores for each tweet
def get_average_weight(self, *a, **kw): res = self.weights.filter(*a, **kw).aggregate(Avg('value')) return res['value__avg']
def get_average_score(self, option, *a, **kw): res = self.scores.filter(option=option, *a, **kw).aggregate(Avg('value')) return res['value__avg']
def get_average_weight(self, *a, **kw): Weight = apps.get_model('ddm_core', 'Weight') res = Weight.objects.filter(criterion__category=self, **kw).aggregate(Avg('value')) return res['value__avg']
def get_average_score(self, option, *a, **kw): Score = apps.get_model('ddm_core', 'Score') res = Score.objects.filter(criterion__category=self, option=option, **kw).aggregate(Avg('value')) return res['value__avg']
def get_average_price(event, start_date, end_date, items, include_pending): tz = pytz.timezone(event.settings.timezone) start_dt = datetime(start_date.year, start_date.month, start_date.day, 0, 0, 0, tzinfo=tz) end_dt = datetime(end_date.year, end_date.month, end_date.day, 23, 59, 59, tzinfo=tz) if include_pending: qs = get_base_queryset(event, items, include_pending).filter( order__datetime__gte=start_dt, order__datetime__lte=end_dt ) else: qs = get_base_queryset(event, items, include_pending).filter( order__payment_date__gte=start_dt, order__payment_date__lte=end_dt ) return round(qs.aggregate(Avg('price')).get('price__avg') or 0, 2)
def get_series_rating(self, series_id): return Video.objects.filter(series=series_id).aggregate(Avg('rating'))['rating__avg']
def get_site_rating(self, site): return Video.objects.filter(site=site).aggregate(Avg('rating'))['rating__avg']
def promedios_por_comercio(request, anio, mes, quincena, region_id=None): return _agregado_por_comercio(request, anio, mes, quincena, region_id, Avg, "promedio_")
def min_max_avg_rate(cls, pair, to_int=None, to_round=None): r = cls.objects.filter(pair=pair).exclude(Q(cancel=True) | Q(completed=True)).aggregate(Avg('rate')) v=[cls.min_buy_rate(pair), cls.max_sale_rate(pair), r.get('rate__avg')] v = [x if not x is None else _Zero for x in v] if to_int: return [x.__int__() for x in v] if to_round: return [round(x, to_round) for x in v] return v
def min_max_avg_rate_hour(cls, pair, to_int=None, to_round=None): obj = cls.last_24_hour().filter(pair=pair).exclude(Q(cancel=True) | Q(completed=True)) if not obj: return 0, 0, 0 r = obj.aggregate(Avg('rate')) v=[cls.min_buy_rate_hour(pair), cls.max_sale_rate_hour(pair), r.get('rate__avg')] v = [x if not x is None else _Zero for x in v] if to_int: return [x.__int__() for x in v] if to_round: return [round(x, to_round) for x in v] return v
def get_context_data(self, *args, **kwargs): context = super(ProductDetailView, self).get_context_data(*args, **kwargs) obj = self.get_object() tags = obj.tag_set.all() rating_avg = obj.productrating_set.aggregate(Avg("rating"), Count("rating")) context["rating_avg"] = rating_avg if self.request.user.is_authenticated(): rating_obj = ProductRating.objects.filter(user=self.request.user, product=obj) if rating_obj.exists(): context['my_rating'] = rating_obj.first().rating for tag in tags: new_view = TagView.objects.add_count(self.request.user.id, tag) return context
def get_today_sales(self): transactions = self.get_transactions_today().aggregate(Sum("price"), Avg("price")) total_sales = transactions["price__sum"] return total_sales
def calculate_average_estimated_time(case_ids): """ Description: Returns an average estimated time for cases. Params: $case_ids - Integer/String: An integer representing the ID in the database. Returns: String: Time in "HH:MM:SS" format. Example: >>> TestCase.calculate_average_time([609, 610, 611]) """ from django.db.models import Avg tcs = TestCase.objects.filter( pk__in=pre_process_ids(case_ids)).only('estimated_time') if not tcs.exists(): raise ValueError('Please input valid case Id') # aggregate avg return integer directly rather than timedelta seconds = tcs.aggregate(Avg('estimated_time')).get('estimated_time__avg') m, s = divmod(seconds, 60) h, m = divmod(m, 60) # TODO: return h:m:s or d:h:m return '%02i:%02i:%02i' % (h, m, s)
def __init__(self, save_path='/Users/u0157492/Projects/moviegeek/builder/models/funkSVD/2017-11-14 22:08:47.116843//model/100/'): self.save_path = save_path self.load_model(save_path) self.avg = list(Rating.objects.all().aggregate(Avg('rating')).values())[0]
def predict_score(self, user_id, item_id): avg_rating = Rating.objects.filter(~Q(user_id=user_id) & Q(movie_id=item_id)).values('movie_id').aggregate(Avg('rating')) return avg_rating['rating__avg']