本文整理汇总了Python中django.db.models.Sum方法的典型用法代码示例。如果您正苦于以下问题:Python models.Sum方法的具体用法?Python models.Sum怎么用?Python models.Sum使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类django.db.models
的用法示例。
在下文中一共展示了models.Sum方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update_equity
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Sum [as 别名]
def update_equity(self):
today, trading = await is_trading_day(datetime.datetime.today().replace(tzinfo=pytz.FixedOffset(480)))
if trading:
logger.info('更新资金净值 %s %s', today, trading)
dividend = Performance.objects.filter(
broker=self.__broker, day__lt=today.date()).aggregate(Sum('dividend'))['dividend__sum']
if dividend is None:
dividend = Decimal(0)
perform = Performance.objects.filter(
broker=self.__broker, day__lt=today.date()).order_by('-day').first()
if perform is None:
unit = Decimal(1000000)
else:
unit = perform.unit_count
nav = self.__current / unit
accumulated = (self.__current - dividend) / (unit - dividend)
Performance.objects.update_or_create(broker=self.__broker, day=today.date(), defaults={
'used_margin': self.__margin,
'capital': self.__current, 'unit_count': unit, 'NAV': nav, 'accumulated': accumulated})
示例2: get_context_data
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Sum [as 别名]
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user = self.request.user
orgas = organization_manager.get_user_organizations(user)
cumulated_turnovers = (orgas
.aggregate(sum=Sum('invoices__total_excl_tax'))["sum"]) or D('0')
cumulated_debts = (orgas
.aggregate(sum=Sum('bills__total_excl_tax'))["sum"]) or D('0')
cumulated_profits = cumulated_turnovers - cumulated_debts
context["organizations_count"] = orgas.count()
context["organizations_cumulated_turnovers"] = cumulated_turnovers
context["organizations_cumulated_profits"] = cumulated_profits
context["organizations_cumulated_active_days"] = 0
context["organizations"] = orgas
context["last_invoices"] = Invoice.objects.all()[:10]
return context
示例3: runindex
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Sum [as 别名]
def runindex(request, event=None):
event = viewutil.get_event(event)
if not event.id:
return HttpResponseRedirect(
reverse('tracker:runindex', args=(Event.objects.latest().short,))
)
searchParams = {}
searchParams['event'] = event.id
runs = filters.run_model_query('run', searchParams)
runs = runs.annotate(hasbids=Sum('bids'))
return views_common.tracker_response(
request, 'tracker/runindex.html', {'runs': runs, 'event': event},
)
示例4: update_total
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Sum [as 别名]
def update_total(self):
if self.istarget:
self.total = self.bids.filter(
donation__transactionstate='COMPLETED'
).aggregate(Sum('amount'))['amount__sum'] or Decimal('0.00')
self.count = self.bids.filter(
donation__transactionstate='COMPLETED'
).count()
# auto close this if it's a challenge with no children and the goal's been met
if (
self.goal
and self.state == 'OPENED'
and self.total >= self.goal
and self.istarget
):
self.state = 'CLOSED'
else:
options = self.options.exclude(
state__in=('HIDDEN', 'DENIED', 'PENDING')
).aggregate(Sum('total'), Sum('count'))
self.total = options['total__sum'] or Decimal('0.00')
self.count = options['count__sum'] or 0
示例5: spending_over_time
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Sum [as 别名]
def spending_over_time(self, request):
fiscal_year = request.query_params.get("fiscal_year")
queryset = self.filter_queryset(self.get_queryset())
if fiscal_year:
start_date, end_date = get_fiscal_year_range(int(fiscal_year))
queryset = queryset.filter(
date_of_grant__gte=start_date, date_of_grant__lte=end_date
)
queryset = (
queryset.without_amendments()
.annotate(month=TruncMonth("date_of_grant"))
.values("month")
.annotate(total=Sum("amount_to_pay"), count=Count("id"))
.values("month", "total", "count")
.order_by("month")
)
return Response(queryset)
示例6: filter_entities
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Sum [as 别名]
def filter_entities(self, queryset, name, value):
if not value:
return queryset
return (
queryset.filter(contract__entity__in=value)
.distinct()
.annotate(
contracts_total=Sum(
"contract__amount_to_pay",
filter=Q(contract__parent=None, contract__entity__in=value),
),
contracts_count=Count(
"contract",
filter=Q(contract__parent=None, contract__entity__in=value),
),
)
)
示例7: filter_entity_by_id
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Sum [as 别名]
def filter_entity_by_id(self, queryset, name, value):
if not value:
return queryset
return (
queryset.filter(contract__entity_id__in=value)
.distinct()
.annotate(
contracts_total=Sum(
"contract__amount_to_pay",
filter=Q(contract__parent=None, contract__entity_id__in=value),
),
contracts_count=Count(
"contract",
filter=Q(contract__parent=None, contract__entity_id__in=value),
),
)
)
示例8: filter_contractors_by_id
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Sum [as 别名]
def filter_contractors_by_id(self, queryset, name, value):
if not value:
return queryset
contracts = Contract.objects.filter(contractors__in=value).only("id")
return (
queryset.filter(contract__in=contracts)
.distinct()
.annotate(
contracts_total=Sum(
"contract__amount_to_pay",
filter=Q(contract__parent=None, contract__in=contracts),
),
contracts_count=Count(
"contract", filter=Q(contract__parent=None, contract__in=contracts)
),
)
)
示例9: test_execute_query_with_wildcard_tag_filter
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Sum [as 别名]
def test_execute_query_with_wildcard_tag_filter(self):
"""Test that data is filtered to include entries with tag key."""
url = "?filter[time_scope_units]=month&filter[time_scope_value]=-1&filter[resolution]=monthly" # noqa: E501
query_params = self.mocked_query_params(url, AWSTagView)
handler = AWSTagQueryHandler(query_params)
tag_keys = handler.get_tag_keys()
filter_key = tag_keys[0]
tag_keys = ["tag:" + tag for tag in tag_keys]
with tenant_context(self.tenant):
totals = AWSCostEntryLineItemDailySummary.objects.filter(
usage_start__gte=self.dh.this_month_start
).aggregate(**{"cost": Sum(F("unblended_cost") + F("markup_cost"))})
url = f"?filter[time_scope_units]=month&filter[time_scope_value]=-1&filter[resolution]=monthly&filter[tag:{filter_key}]=*" # noqa: E501
query_params = self.mocked_query_params(url, AWSCostView)
handler = AWSReportQueryHandler(query_params)
data = handler.execute_query()
data_totals = data.get("total", {})
result = data_totals.get("cost", {}).get("total", {}).get("value")
self.assertEqual(result, totals["cost"])
示例10: test_execute_query_with_wildcard_tag_filter
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Sum [as 别名]
def test_execute_query_with_wildcard_tag_filter(self):
"""Test that data is filtered to include entries with tag key."""
# Pick tags for the same month we query on later
url = "?filter[time_scope_units]=month&filter[time_scope_value]=-1&filter[resolution]=monthly"
query_params = self.mocked_query_params(url, AzureTagView)
handler = AzureTagQueryHandler(query_params)
tag_keys = handler.get_tag_keys()
filter_key = tag_keys[0]
tag_keys = ["tag:" + tag for tag in tag_keys]
ag_key = "cost_total"
with tenant_context(self.tenant):
totals = AzureCostEntryLineItemDailySummary.objects.filter(
usage_start__gte=self.dh.this_month_start
).aggregate(**{ag_key: Sum(F("pretax_cost") + F("markup_cost"))})
url = f"?filter[time_scope_units]=month&filter[time_scope_value]=-1&filter[resolution]=monthly&filter[tag:{filter_key}]=*" # noqa: E501
query_params = self.mocked_query_params(url, AzureCostView)
handler = AzureReportQueryHandler(query_params)
data = handler.execute_query()
data_totals = data.get("total", {})
result = data_totals.get("cost", {}).get("total")
self.assertIsNotNone(result)
self.assertAlmostEqual(result.get("value"), totals[ag_key], 6)
示例11: test_populate_markup_cost_no_billsids
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Sum [as 别名]
def test_populate_markup_cost_no_billsids(self):
"""Test that the daily summary table is populated."""
summary_table_name = AZURE_REPORT_TABLE_MAP["line_item_daily_summary"]
summary_table = getattr(self.accessor.report_schema, summary_table_name)
query = self.accessor._get_db_obj_query(summary_table_name)
with schema_context(self.schema):
expected_markup = query.aggregate(markup=Sum(F("pretax_cost") * decimal.Decimal(0.1)))
expected_markup = expected_markup.get("markup")
summary_entry = summary_table.objects.all().aggregate(Min("usage_start"), Max("usage_start"))
start_date = summary_entry["usage_start__min"]
end_date = summary_entry["usage_start__max"]
self.accessor.populate_markup_cost(0.1, start_date, end_date, None)
with schema_context(self.schema):
query = self.accessor._get_db_obj_query(summary_table_name).aggregate(Sum("markup_cost"))
actual_markup = query.get("markup_cost__sum")
self.assertAlmostEqual(actual_markup, expected_markup, 6)
示例12: test_populate_markup_cost_no_billsids
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Sum [as 别名]
def test_populate_markup_cost_no_billsids(self):
"""Test that the daily summary table is populated."""
summary_table_name = AWS_CUR_TABLE_MAP["line_item_daily_summary"]
summary_table = getattr(self.accessor.report_schema, summary_table_name)
query = self.accessor._get_db_obj_query(summary_table_name)
with schema_context(self.schema):
expected_markup = query.aggregate(markup=Sum(F("unblended_cost") * decimal.Decimal(0.1)))
expected_markup = expected_markup.get("markup")
summary_entry = summary_table.objects.all().aggregate(Min("usage_start"), Max("usage_start"))
start_date = summary_entry["usage_start__min"]
end_date = summary_entry["usage_start__max"]
self.accessor.populate_markup_cost(0.1, start_date, end_date, None)
with schema_context(self.schema):
query = self.accessor._get_db_obj_query(summary_table_name).aggregate(Sum("markup_cost"))
actual_markup = query.get("markup_cost__sum")
self.assertAlmostEqual(actual_markup, expected_markup, 6)
示例13: calculate_credit
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Sum [as 别名]
def calculate_credit(self, user, start, end):
"""
Calculate approved days of type for user in given time frame.
For absence types which fill worktime this will be None.
"""
if self.fill_worktime:
return None
credits = AbsenceCredit.objects.filter(
user=user, absence_type=self, date__range=[start, end]
)
data = credits.aggregate(credit=Sum("days"))
credit = data["credit"] or 0
return credit
示例14: get_context_data
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Sum [as 别名]
def get_context_data(self, **kwargs):
context = super(IncomeExpenseReport, self).get_context_data(**kwargs)
queryset = Split.objects.past().order_by()
incomes = queryset.income().annotate(m=TruncMonth('date')).values('m').annotate(
total=models.Sum('amount'))
expenses = queryset.expense().annotate(m=TruncMonth('date')).values('m').annotate(
total=models.Sum('amount'))
result = []
for i, e in zip(incomes, expenses):
result.append({
'month': i['m'],
'income': i['total'],
'expense': e['total'],
'total': i['total'] + e['total']
})
context['result'] = result
return context
示例15: get_balances
# 需要导入模块: from django.db import models [as 别名]
# 或者: from django.db.models import Sum [as 别名]
def get_balances(request, dstart, dend):
try:
dstart = datetime.datetime.strptime(dstart, '%Y-%m-%d').date()
dend = datetime.datetime.strptime(dend, '%Y-%m-%d').date()
except ValueError:
return HttpResponseBadRequest(_('Invalid date format, expected yyyy-mm-dd'))
balance = Split.objects.personal().exclude_transfers().filter(date__lt=dstart).aggregate(
models.Sum('amount'))['amount__sum'] or 0
splits = Split.objects.personal().exclude_transfers().date_range(dstart, dend).order_by('date')
data_points = []
labels = []
days = (dend - dstart).days
if days > 50:
step = days / 50 + 1
else:
step = 1
for split in splits:
while split.date > dstart:
data_points.append(balance)
labels.append(datetime.datetime.strftime(dstart, '%Y-%m-%d'))
dstart += datetime.timedelta(days=step)
balance += split.amount
data_points.append(balance)
labels.append(datetime.datetime.strftime(dend, '%Y-%m-%d'))
return JsonResponse({'labels': labels, 'data': data_points})