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.
170 Examples
3
Example 1
Project: Truthbot.org Source File: tasks.py
@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()
3
Example 2
def handle(self, *args, **options):
for link in Link.objects.all():
link.vote_score = \
link.votes.aggregate(score=Sum('value'))['score'] or 0
link.comment_score = link.comment_set.all().count()
link.save()
3
Example 3
Project: cito_engine Source File: actions.py
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
3
Example 4
Project: zipfelchappe Source File: models.py
@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
3
Example 5
@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
3
Example 6
Project: django-calaccess-campaign-browser Source File: filings.py
@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']
3
Example 7
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
3
Example 8
Project: cartridge Source File: models.py
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
3
Example 9
Project: META-SHARE Source File: model_utils.py
def getLRStats(lrid):
data = ""
action_list = LRStats.objects.values('lrid', 'action').filter(lrid=lrid, ignored=False).annotate(Count('action'), Sum('count')).order_by('-action')
if (action_list.count() > 0):
for key in action_list:
sets = LRStats.objects.values('lasttime').filter(lrid=lrid, action=str(key['action'])).order_by('-lasttime')[:1]
for key2 in sets:
if str(key['action']) in VISIBLE_STATS:
if (len(data) > 0):
data += ", "
data += "{\"action\":\""+ STAT_LABELS[str(key['action'])] +"\",\"count\":\""+ \
str(key['count__sum']) +"\",\"last\":\""+str(key2['lasttime'])[:10]+"\"}"
break
return json.loads("["+data+"]")
3
Example 10
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
3
Example 11
Project: akvo-rsr Source File: organisation.py
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
3
Example 12
Project: django-oscar-accounts Source File: reports.py
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')
3
Example 13
Project: Roll-Your-Own Source File: tests.py
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'])
3
Example 14
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")))
3
Example 15
Project: SchoolIdolAPI Source File: views.py
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)
3
Example 16
Project: cointrol Source File: tests.py
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
3
Example 17
Project: django-calaccess-raw-data Source File: tracking.py
@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']
3
Example 18
Project: UDJ-Server Source File: playlistalgos.py
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)
3
Example 19
Project: django-shop Source File: delivery.py
@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
3
Example 20
Project: META-SHARE Source File: model_utils.py
def get_lr_stat_action_count(obj_identifier, stats_action):
"""
Returns the count of the given stats action for the given resource instance.
The obj_identifier is the identifier from the storage object.
"""
result = LRStats.objects.filter(lrid=obj_identifier, action=stats_action) \
.aggregate(Sum('count'))['count__sum']
# `result` may be None in case the filter doesn't match any LRStats for the
# specified resource and action
if result is not None:
return result
else:
return 0
3
Example 21
Project: django-generic-aggregation Source File: tests.py
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)
3
Example 22
@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
3
Example 23
Project: villagescc Source File: audit.py
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
3
Example 24
Project: django Source File: tests.py
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)
)
3
Example 25
Project: wagtail Source File: models.py
@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'))
3
Example 26
Project: akvo-rsr Source File: organisation.py
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
3
Example 27
Project: djangogirls Source File: context_processors.py
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
}
3
Example 28
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()
3
Example 29
Project: djep Source File: models.py
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
3
Example 30
Project: neo4django Source File: nodequeryset_tests.py
@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)
3
Example 31
Project: courtlistener Source File: models.py
@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
3
Example 32
Project: django-event-rsvp Source File: models.py
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.')
3
Example 33
Project: euscan Source File: managers.py
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
3
Example 34
Project: django-shop Source File: cart.py
@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
3
Example 35
Project: django-sharding Source File: test_router.py
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)
3
Example 36
Project: django-calaccess-raw-data Source File: tracking.py
@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']
3
Example 37
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)
3
Example 38
Project: baruwa Source File: utils.py
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
3
Example 39
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")
)
3
Example 40
Project: django-pandas Source File: test_io.py
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"]))
3
Example 41
Project: Politikon Source File: models.py
@property
def current_total_cash(self):
"""
Calculate current total_cash
:return: total_cash value
:rtype: int
"""
return Transaction.objects.get_user_transactions_after_reset(user=self).\
aggregate(sum=Sum('price'))['sum']
3
Example 42
Project: jmbo Source File: models.py
@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
3
Example 43
Project: django-banner-rotator Source File: managers.py
def biased_choice(self, place):
queryset = self.filter(is_active=True, places=place)
if not queryset.count():
raise self.model.DoesNotExist
normalizer = queryset.aggregate(normalizer=models.Sum('weight'))['normalizer']
return pick([(i, i.weight / float(normalizer)) for i in queryset])
3
Example 44
Project: iCQA Source File: admin.py
@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'))
3
Example 45
Project: amy Source File: views.py
@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 cuemulative generator over the data
data = accuemulate(serializer.data, self._add_counts)
data = self.listify(data, request, format)
return Response(data)
3
Example 46
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")
)
3
Example 47
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()
3
Example 48
Project: readthedocs.org Source File: mixins.py
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
3
Example 49
Project: daywatch Source File: analytics.py
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])
3
Example 50
Project: site Source File: stats.py
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)