django.db.models.Sum

Here are the examples of the python api django.db.models.Sum taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

200 Examples 7

Example 1

Project: pinax-stripe
Source File: managers.py
View license
    def paid_totals_for(self, year, month):
        return self.during(year, month).filter(
            paid=True
        ).aggregate(
            total_amount=models.Sum("amount"),
            total_refunded=models.Sum("amount_refunded")
        )

Example 2

Project: jmbo
Source File: models.py
View license
    @property
    def _vote_total(self):
        """
        Calculates vote total (+1 for upvote and -1 for downvote). We are
        adding a method here instead of relying on django-secretballot's
        addition since that doesn't work for subclasses.
        """
        votes = Vote.objects.filter(object_id= \
            self.id).aggregate(Sum('vote'))['vote__sum']
        return votes if votes else 0

Example 3

Project: Misago
Source File: models.py
View license
    def synchronize(self):
        threads_queryset = self.thread_set.filter(is_hidden=False, is_unapproved=False)
        self.threads = threads_queryset.count()

        if self.threads:
            replies_sum = threads_queryset.aggregate(models.Sum('replies'))
            self.posts = self.threads + replies_sum['replies__sum']
        else:
            self.posts = 0

        if self.threads:
            last_thread_qs = threads_queryset.filter(is_hidden=False, is_unapproved=False)
            last_thread = last_thread_qs.order_by('-last_post_on')[:1][0]
            self.set_last_thread(last_thread)
        else:
            self.empty_last_thread()

Example 4

Project: django-shop
Source File: cart.py
View license
    @property
    def total_quantity(self):
        """
        Returns the total quantity of all items in the cart.
        """
        aggr = self.items.aggregate(quantity=models.Sum('quantity'))
        return aggr['quantity'] or 0

Example 5

Project: django-shop
Source File: delivery.py
View license
    @cached_property
    def unfulfilled_items(self):
        unfulfilled_items = 0
        for order_item in self.items.all():
            if not order_item.canceled:
                aggr = order_item.deliveryitem_set.aggregate(delivered=Sum('quantity'))
                unfulfilled_items += order_item.quantity - (aggr['delivered'] or 0)
        return unfulfilled_items

Example 6

Project: villagescc
Source File: audit.py
View license
def account_check(account):
    """
    Returns True if account balance is the sum of all entries.
    Otherwise raises AuditError.
    """
    entry_sum = (
        account.entries.all().aggregate(Sum('amount'))['amount__sum'] or D('0'))
    if entry_sum != account.balance:
        raise AuditError(
            "%s out of balance: balance is %s; entry sum is %s" % (
                account, account.balance, entry_sum))
    return True

Example 7

Project: readthedocs.org
Source File: mixins.py
View license
    def get_context_data(self, **kwargs):
        context = super(DonateProgressMixin, self).get_context_data(**kwargs)
        sums = (Supporter.objects
                .aggregate(dollars=Sum('dollars')))
        avgs = (Supporter.objects
                .aggregate(dollars=Avg('dollars')))
        dollars = sums.get('dollars', None) or 0
        avg = int(avgs.get('dollars', None) or 0)
        count = Supporter.objects.count()
        percent = int((float(dollars) / 24000.0) * 100.0)
        context.update({
            'donate_amount': dollars,
            'donate_avg': avg,
            'donate_percent': percent,
            'donate_count': count,
        })
        return context

Example 8

Project: neo4django
Source File: nodequeryset_tests.py
View license
@with_setup(setup_people, teardown)
def test_aggregate_sum():
    from django.db.models import Sum

    eq_(Person.objects.all().aggregate(Sum('age')).get('age__sum', None), 75)
    eq_(Person.objects.all().filter(name='Candleja-').aggregate(Sum('age')).get('age__sum', None), 30)

Example 9

Project: SchoolIdolAPI
Source File: views.py
View license
def results_index_view(request):
    context = globalContext(request)
    if settings.HIGH_TRAFFIC:
        return render(request, 'disabled.html', context)
    queryset = past_contests_queryset().annotate(count=Sum('votes__counter')).select_related('suggested_by', 'image_by')
    now = datetime.datetime.now()
    total_votes = contest_models.Vote.objects.filter(contest__end__lte=now).values('contest_id').annotate(total_votes=Sum('counter')).order_by('-contest__end')
    contests = [(contest, best_single_cards(contest), total_votes['total_votes']) for contest, total_votes in zip(queryset, total_votes)]
    context.update({
        'contests': contests,
        'current': 'past_contests',
    })
    return render(request, 'contest_result_index.html', context)

Example 10

Project: baruwa
Source File: utils.py
View license
def run_hosts_query(request, active_filters):
    "run the top hosts query"
    data = Message.messages.for_user(request).values('clientip').exclude(
        Q(clientip__exact='') | Q(clientip__exact='127.0.0.1') |
        Q(clientip__isnull=True)).annotate(num_count=Count('clientip'),
        total_size=Sum('size'), virus_total=Sum('virusinfected'),
        spam_total=Sum('spam')).order_by('-num_count')
    data = apply_filter(data, request, active_filters)
    data = data[:10]
    return data

Example 11

Project: cartridge
Source File: models.py
View license
    def live_num_in_stock(self):
        """
        Returns the live number in stock, which is
        ``self.num_in_stock - num in carts``. Also caches the value
        for subsequent lookups.
        """
        if self.num_in_stock is None:
            return None
        if not hasattr(self, "_cached_num_in_stock"):
            num_in_stock = self.num_in_stock
            carts = Cart.objects.current()
            items = CartItem.objects.filter(sku=self.sku, cart__in=carts)
            aggregate = items.aggregate(quantity_sum=models.Sum("quantity"))
            num_in_carts = aggregate["quantity_sum"]
            if num_in_carts is not None:
                num_in_stock = num_in_stock - num_in_carts
            self._cached_num_in_stock = num_in_stock
        return self._cached_num_in_stock

Example 12

Project: amy
Source File: views.py
View license
    @list_route(methods=['GET'])
    def learners_over_time(self, request, format=None):
        """Cumulative number of learners attending Software-Carpentry and other
        carpentries' workshops over time."""
        qs = self.event_queryset
        qs = LearnersOverTimeFilter(request.GET, queryset=qs).qs
        qs = qs.annotate(count=Sum('attendance'))

        # we reuse the serializer because it works here too
        serializer = WorkshopsOverTimeSerializer(qs, many=True)

        # run a cumulative generator over the data
        data = accumulate(serializer.data, self._add_counts)

        data = self.listify(data, request, format)

        return Response(data)

Example 13

Project: bookkeeper
Source File: account_api.py
View license
    def balance(self, date=None):
        """ returns the account balance as of 'date' (datetime stamp) or now().  """

        qs = self._entries()
        if date:
            qs = qs.filter(transaction__t_stamp__lt=date)
        r = qs.aggregate(b=Sum('amount'))
        b = r['b']

        flip = self._DEBIT_IN_DB()
        if self._positive_credit():
            flip *= -1

        if b is None:
            b = Decimal("0.00")
        b *= flip

        #print "returning balance %s for %s" % (b, self)
        return b

Example 14

Project: wagtail
Source File: models.py
View license
    @classmethod
    def get_most_popular(cls, date_since=None):
        # TODO: Implement date_since
        return (cls.objects.filter(daily_hits__isnull=False)
                .annotate(_hits=models.Sum('daily_hits__hits'))
                .distinct().order_by('-_hits'))

Example 15

Project: daywatch
Source File: analytics.py
View license
def total_sales(items):
    """The total sales for all items."""
    try:
        return items.aggregate(total=Sum('sold_count',
                                         field='sold_count*price'))['total']
    except:
        return sum([item.sold_count*item.price for item in
                    items if
                    item.sold_count is not None and
                    item.price is not None])

Example 16

Project: django-star-ratings
Source File: models.py
View license
    def calculate(self):
        """
        Recalculate the totals, and save.
        """
        aggregates = self.user_ratings.aggregate(total=Sum('score'), average=Avg('score'), count=Count('score'))
        self.count = aggregates.get('count') or 0
        self.total = aggregates.get('total') or 0
        self.average = aggregates.get('average') or 0.0
        self.save()

Example 17

Project: Roll-Your-Own
Source File: tests.py
View license
    def test_model_cache_aggregation(self):
        """ Checks that aggregation works with cached summary totals. """
        # Add another model instance and test aggregation
        cart2 = Cart.objects.create()
        item_1    = CartItem.objects.create(cart=cart2, product=self.product_1)
        cart_summary2 = CartSummary(instance=cart2)

        cached_total = self.cart_summary.cached_total + cart_summary2.cached_total
        self.cart.save()
        cart2.save()

        self.assertEqual(cached_total, Cart.objects.all().aggregate(cached_sum=Sum('cached_total'))['cached_sum'])

Example 18

Project: django-event-rsvp
Source File: models.py
View license
    def get_free_seats(self):
        reserved = self.guests.all().aggregate(models.Sum('number_of_seats'))
        if self.available_seats:
            return self.available_seats - int(reserved.get(
                'number_of_seats__sum') or 0)
        return _('Unlimited seats available.')

Example 19

View license
    @property
    def total_expenditures(self):
        if self.is_quarterly:
            summary = self.summary
            if summary:
                return summary.total_expenditures
            else:
                return None
        elif self.is_late:
            return Expenditure.real.filter(
                filing=self
            ).aggregate(total=Sum('amount'))['total']

Example 20

View license
    @property
    def download_record_count(self):
        """
        Returns the count of records in the version's downloaded files.
        """
        return self.files.aggregate(
            total=models.Sum('download_records_count')
        )['total']

Example 21

View license
    @property
    def clean_record_count(self):
        """
        Returns the count of records in the version's cleaned files.
        """
        return self.files.aggregate(
            total=models.Sum('clean_records_count')
        )['total']

Example 22

Project: django-pandas
Source File: test_io.py
View license
    def test_values(self):
        qs = MyModel.objects.all()
        qs = qs.extra(select={"ecol1": "col1+1"})
        qs = qs.values("index_col", "ecol1", "col1")
        qs = qs.annotate(scol1=Sum("col1"))
        df = read_frame(qs)
        self.assertEqual(list(df.columns),
                         ['index_col', 'col1', 'scol1', 'ecol1'])
        self.assertEqual(list(df["col1"]), list(df["scol1"]))

Example 23

Project: cito_engine
Source File: actions.py
View license
def get_most_alerted_elements(days, result_limit=10):
    """
    Get most alerted elements
    :param days:
    :param result_limit:
    :return:
    """
    time_range = timezone.make_aware(datetime.today() - timedelta(days=days), timezone.get_current_timezone())
    elements_by_unique_incidents = Incident.objects.values('element'). \
                                       filter(firstEventTime__gte=time_range). \
                                       annotate(uniq_count=Count('id'), total_count=Sum('total_incidents')). \
                                       order_by('-uniq_count')[:result_limit]
    return elements_by_unique_incidents

Example 24

Project: iCQA
Source File: admin.py
View license
@super_user_required
def recalculate_denormalized(request):
    for n in Node.objects.all():
        n = n.leaf
        n.score = n.votes.aggregate(score=models.Sum('value'))['score']
        if not n.score: n.score = 0
        n.save()

    for u in User.objects.all():
        u.reputation = u.reputes.aggregate(reputation=models.Sum('value'))['reputation']
        u.save()

    request.user.message_set.create(message=_('All values recalculated'))
    return HttpResponseRedirect(reverse('admin_index'))

Example 25

Project: django-generic-aggregation
Source File: tests.py
View license
    def test_subset_aggregation(self):
        todays_ratings = Rating.objects.filter(created__gte=datetime.date.today())
        aggregated = self.generic_aggregate(Food.objects.all(), todays_ratings, models.Sum('ratings__rating'))
        self.assertEqual(aggregated, 15)

        aggregated = self.generic_aggregate(Food.objects.all(), todays_ratings, models.Count('ratings__rating'))
        self.assertEqual(aggregated, 4)

Example 26

Project: crate-site
Source File: models.py
View license
    @property
    def downloads(self):
        KEY = "crate:packages:package:%s:downloads" % self.pk

        total_downloads = cache.get(KEY)
        if total_downloads is None:
            total_downloads = ReleaseFile.objects.filter(release__package=self).aggregate(total_downloads=Sum("downloads"))["total_downloads"]
            if total_downloads is None:
                total_downloads = 0

            cache.set(KEY, total_downloads)
        return total_downloads

Example 27

Project: crate-site
Source File: models.py
View license
    @property
    def downloads(self):
        KEY = "crate:packages:release:%s:downloads" % self.pk

        total_downloads = cache.get(KEY)

        if total_downloads is None:
            total_downloads = self.files.aggregate(total_downloads=Sum("downloads"))["total_downloads"]
            if total_downloads is None:
                total_downloads = 0
            cache.set(KEY, total_downloads)

        return total_downloads

Example 28

Project: crate.web
Source File: models.py
View license
    @property
    def downloads(self):
        KEY = "crate:packages:package:%s:downloads" % self.pk

        total_downloads = cache.get(KEY)
        if total_downloads is None:
            total_downloads = ReleaseFile.objects.filter(release__package=self).aggregate(total_downloads=Sum("downloads"))["total_downloads"]
            if total_downloads is None:
                total_downloads = 0

            cache.set(KEY, total_downloads)
        return total_downloads

Example 29

Project: crate.web
Source File: models.py
View license
    @property
    def downloads(self):
        KEY = "crate:packages:release:%s:downloads" % self.pk

        total_downloads = cache.get(KEY)

        if total_downloads is None:
            total_downloads = self.files.aggregate(total_downloads=Sum("downloads"))["total_downloads"]
            if total_downloads is None:
                total_downloads = 0
            cache.set(KEY, total_downloads)

        return total_downloads

Example 30

Project: django
Source File: tests.py
View license
    def test_annotate_defer(self):
        qs = Book.objects.annotate(
            page_sum=Sum("pages")).defer('name').filter(pk=self.b1.pk)

        rows = [
            (1, "159059725", 447, "The Definitive Guide to Django: Web Development Done Right")
        ]
        self.assertQuerysetEqual(
            qs.order_by('pk'), rows,
            lambda r: (r.id, r.isbn, r.page_sum, r.name)
        )

Example 31

Project: django-oscar-accounts
Source File: reports.py
View license
    def transfer_total(self, qs):
        filters = {
            'date_created__gte': self.start,
            'date_created__lt': self.end}
        transfers = qs.filter(**filters)
        total = transfers.aggregate(sum=Sum('amount'))['sum']
        return total if total is not None else D('0.00')

Example 32

Project: djangogirls
Source File: context_processors.py
View license
def statistics(request):
    future_events = Event.objects.future()
    past_events = Event.objects.past()
    countries = Event.objects.values('country').distinct()
    attendees = Postmortem.objects.all().aggregate(attendees=Sum('attendees_count'), applicants=Sum('applicants_count'))
    meetup_count = Meetup.visible_objects.count()

    return {
        'past_events_count': past_events.count(),
        'future_events_count': future_events.count(),
        'all_events_count': past_events.count() + future_events.count(),
        'countries_count': countries.count(),
        'attendees_sum': attendees['attendees'],
        'applicants_sum': attendees['applicants'],
        'meetup_count': meetup_count
    }

Example 33

Project: site
Source File: stats.py
View license
def language_data(request, language_count=Language.objects.annotate(count=Count('submission'))):
    languages = language_count.filter(count__gte=1000).values('key', 'name', 'short_name', 'count').order_by('-count')
    data = []
    for language, color, highlight in zip(languages, chart_colors, highlight_colors):
        data.append({
            'value': language['count'], 'label': language['name'],
            'color': color, 'highlight': highlight,
        })
    data.append({
        'value': language_count.filter(count__lt=1000).aggregate(total=Sum('count'))['total'],
        'label': 'Other', 'color': '#FDB45C', 'highlight': '#FFC870',
    })
    return JsonResponse(data, safe=False)

Example 34

Project: akvo-rsr
Source File: organisation.py
View license
    def euros_pledged(self):
        "How much € the organisation has pledged to projects it is a partner to"
        return self.active_projects().euros().filter(
            partnerships__organisation__exact=self,
            partnerships__iati_organisation_role__exact=Partnership.IATI_FUNDING_PARTNER
        ).aggregate(
            euros_pledged=Sum('partnerships__funding_amount')
        )['euros_pledged'] or 0

Example 35

Project: akvo-rsr
Source File: organisation.py
View license
    def dollars_pledged(self):
        "How much $ the organisation has pledged to projects"
        return self.active_projects().dollars().filter(
            partnerships__organisation__exact=self,
            partnerships__iati_organisation_role__exact=Partnership.IATI_FUNDING_PARTNER
        ).aggregate(
            dollars_pledged=Sum('partnerships__funding_amount')
        )['dollars_pledged'] or 0

Example 36

Project: djep
Source File: models.py
View license
    def calculate_payment_total(self, tickets=None):
        # TODO: Externalize this into a utils method to be usable "offline"
        # TODO Maybe it's necessary to add VAT to payment_total.
        # TKO: Nope: in 2013 at least all ticket prices have been including VAT
        # However this may be different if people from foreign countries purchase
        # a ticket because then no VAT may be added (depends on country...)
        # so remains TODO for EuroPython
        fee_sum = 0.0
        if tickets is None:
            fee_sum = self.ticket_set.aggregate(models.Sum('ticket_type__fee'))
            return fee_sum['ticket_type__fee__sum']
        else:
            for ticket in tickets:
                fee_sum += ticket.ticket_type.fee
            return fee_sum

Example 37

Project: zipfelchappe
Source File: models.py
View license
    @cached_property
    def achieved(self):
        """
        Returns the amount of money raised
        :return: Amount raised
        """
        amount = self.authorized_pledges.aggregate(Sum('amount'))
        return amount['amount__sum'] or 0

Example 38

Project: courtlistener
Source File: models.py
View license
    @property
    def total_donated(self):
        total = self.user.donations.exclude(
            status__in=donation_exclusion_codes
        ).aggregate(Sum('amount'))['amount__sum']
        if total is None:
            total = Decimal(0.0)
        return total

Example 39

Project: sfm-ui
Source File: models.py
View license
    def stats(self):
        """
        Returns a dict of items to count.
        """
        return _item_counts_to_dict(
            HarvestStat.objects.filter(harvest__collection=self).values("item").annotate(count=models.Sum("count")))

Example 40

Project: euscan
Source File: managers.py
View license
def _gen_n_function(field_name):
    def n_method(self):
        res = self.aggregate(models.Sum(field_name))[field_name + '__sum']
        return xint(res)
    n_method.func_name = field_name
    return n_method

Example 41

Project: Truthbot.org
Source File: tasks.py
View license
@shared_task
def compute_score(user):
    user = User.objects.get(pk=user)
    post_score_sum = Post.objects.filter(author=user).aggregate(Sum('score'))['score__sum'] or 0
    comment_score_sum = Comment.objects.filter(author=user).aggregate(Sum('score'))['score__sum'] or 0
    comment_replies_sum = CommentReply.objects.filter(author=user).count()
    wiki_edit_sum = OrganizationWiki.objects.filter(contributors=user).count() * 5
    reversion_sum = Revision.objects.filter(user=user).count()

    score = post_score_sum + comment_score_sum + comment_replies_sum + wiki_edit_sum + reversion_sum

    c = Contributor.objects.get(user=user)
    c.points = score
    c.save()

Example 42

Project: django-sharding
Source File: test_router.py
View license
    def test_queryset_router_filter_with_aggregates(self):
        for i in range(1, 11):
            TestModel.objects.create(user_pk=self.user.pk, random_string="%s" % i)
        num_models = TestModel.objects.filter(user_pk=self.user.pk).count()
        self.assertEqual(num_models, 10)

        sum_model_pk = TestModel.objects.filter(user_pk=self.user.pk).aggregate(user_pk_sum=Sum('user_pk'))
        self.assertEqual(sum_model_pk['user_pk_sum'], self.user.pk * 10)

Example 43

Project: cointrol
Source File: tests.py
View license
def test_balance_for_each_transaction():
    print()
    for t in Transaction.objects.order_by('datetime'):
        aggregate = Transaction.objects\
            .filter(datetime__lte=t.datetime)\
            .aggregate(
                usd=Sum('usd'),
                btc=Sum('btc'),
                fee=Sum('fee')
        )
        print('{id: >10} {btc: >18} {usd: >18} {fee: >18} {after_fee}'.format(
            id=t.pk,
            usd=aggregate['usd'],
            btc=aggregate['btc'],
            fee=aggregate['fee'],
            after_fee=aggregate['usd'] - aggregate['fee'],
        ))
        assert aggregate['usd'] >= 0
        assert aggregate['btc'] >= 0

Example 44

Project: cointrol
Source File: tests.py
View license
def test_balance_for_each_transaction():
    print()
    for t in Transaction.objects.order_by('datetime'):
        aggregate = Transaction.objects\
            .filter(datetime__lte=t.datetime)\
            .aggregate(
                usd=Sum('usd'),
                btc=Sum('btc'),
                fee=Sum('fee')
        )
        print('{id: >10} {btc: >18} {usd: >18} {fee: >18} {after_fee}'.format(
            id=t.pk,
            usd=aggregate['usd'],
            btc=aggregate['btc'],
            fee=aggregate['fee'],
            after_fee=aggregate['usd'] - aggregate['fee'],
        ))
        assert aggregate['usd'] >= 0
        assert aggregate['btc'] >= 0

Example 45

Project: johnny-cache
Source File: cache.py
View license
    def test_aggregate_annotation(self):
        """Test aggregating an annotation """
        author_count = Book.objects.annotate(author_count=Count('authors')).aggregate(Sum('author_count'))
        self.assertEqual(author_count['author_count__sum'], 2)
        # also test using the paginator, although this shouldn't be a big issue..
        books = Book.objects.all().annotate(num_authors=Count('authors'))
        paginator = Paginator(books, 25)
        list_page = paginator.page(1)

Example 46

Project: intranet
Source File: admin.py
View license
    def get_results(self, *args, **kwargs):
        super(InvoiceChangeList, self).get_results(*args, **kwargs)

        self.totals = {}
        if hasattr(self, 'columns_with_total'):
            for column_info in self.columns_with_total:
                #In autoreports listing this generates an error
                try:
                    q = self.result_list.aggregate(quantity_sum=Sum(column_info['column']))
                    total = q['quantity_sum']
                    self.totals[column_info['name']] = column_info['lambda'](total)
                except:
                    pass

Example 47

Project: intranet
Source File: admin.py
View license
    def get_results(self, *args, **kwargs):
        super(InvoiceChangeList, self).get_results(*args, **kwargs)

        self.totals = {}
        if hasattr(self, 'columns_with_total'):
            for column_info in self.columns_with_total:
                #In autoreports listing this generates an error
                try:
                    q = self.result_list.aggregate(quantity_sum=Sum(column_info['column']))
                    total = q['quantity_sum']
                    self.totals[column_info['name']] = column_info['lambda'](total)
                except:
                    pass

Example 48

Project: dj-stripe
Source File: managers.py
View license
    def paid_totals_for(self, year, month):
        return self.during(year, month).filter(
            status="paid"
        ).aggregate(
            total_gross=models.Sum("charge_gross"),
            total_net=models.Sum("net"),
            total_charge_fees=models.Sum("charge_fees"),
            total_adjustment_fees=models.Sum("adjustment_fees"),
            total_refund_gross=models.Sum("refund_gross"),
            total_refund_fees=models.Sum("refund_fees"),
            total_validation_fees=models.Sum("validation_fees"),
            total_amount=models.Sum("amount")
        )

Example 49

Project: dj-stripe
Source File: managers.py
View license
    def paid_totals_for(self, year, month):
        return self.during(year, month).filter(
            status="paid"
        ).aggregate(
            total_gross=models.Sum("charge_gross"),
            total_net=models.Sum("net"),
            total_charge_fees=models.Sum("charge_fees"),
            total_adjustment_fees=models.Sum("adjustment_fees"),
            total_refund_gross=models.Sum("refund_gross"),
            total_refund_fees=models.Sum("refund_fees"),
            total_validation_fees=models.Sum("validation_fees"),
            total_amount=models.Sum("amount")
        )

Example 50

Project: UDJ-Server
Source File: playlistalgos.py
View license
def bayesianAverage(queuedEntries):
  def rating_sum(entry1, entry2):
    return entry1.rating + entry2.rating

  def numvotes_sum(entry1, entry2):
    return entry1.numvotes + entry2.numvotes


  queuedEntries = queuedEntries.annotate(rating=Sum('vote__weight')).annotate(numvotes=Count('vote')).order_by('time_added')
  num_entries = len(queuedEntries)
  avg_rating = reduce(rating_sum, queuedEntries) / num_entries
  avg_num_votes = reduce(numvotes_sum, queuedEntries) / num_entries
  avg_quantity = avg_rating * avg_num_votes
  for entry in queuedEntries:
    entry.bayesianAverage = (avg_quantity + (entry.numvotes * entry.rating)) / (avg_num_votes + entry.numvotes)

  return sorted(queuedEntries, key=lambda entry: entry.bayesianAverage)