當前位置: 首頁>>代碼示例>>Python>>正文


Python models.Sum方法代碼示例

本文整理匯總了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}) 
開發者ID:BigBrotherTrade,項目名稱:trader,代碼行數:21,代碼來源:brother2.py

示例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 
開發者ID:dulacp,項目名稱:django-accounting,代碼行數:22,代碼來源:views.py

示例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},
    ) 
開發者ID:GamesDoneQuick,項目名稱:donation-tracker,代碼行數:19,代碼來源:public.py

示例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 
開發者ID:GamesDoneQuick,項目名稱:donation-tracker,代碼行數:24,代碼來源:bid.py

示例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) 
開發者ID:Code4PuertoRico,項目名稱:contratospr-api,代碼行數:23,代碼來源:viewsets.py

示例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),
                ),
            )
        ) 
開發者ID:Code4PuertoRico,項目名稱:contratospr-api,代碼行數:19,代碼來源:filters.py

示例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),
                ),
            )
        ) 
開發者ID:Code4PuertoRico,項目名稱:contratospr-api,代碼行數:20,代碼來源:filters.py

示例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)
                ),
            )
        ) 
開發者ID:Code4PuertoRico,項目名稱:contratospr-api,代碼行數:21,代碼來源:filters.py

示例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"]) 
開發者ID:project-koku,項目名稱:koku,代碼行數:23,代碼來源:tests_queries.py

示例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) 
開發者ID:project-koku,項目名稱:koku,代碼行數:27,代碼來源:tests_azure_query_handler.py

示例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) 
開發者ID:project-koku,項目名稱:koku,代碼行數:20,代碼來源:test_azure_report_db_accessor.py

示例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) 
開發者ID:project-koku,項目名稱:koku,代碼行數:21,代碼來源:test_aws_report_db_accessor.py

示例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 
開發者ID:adfinis-sygroup,項目名稱:timed-backend,代碼行數:18,代碼來源:models.py

示例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 
開發者ID:agstrike,項目名稱:silverstrike,代碼行數:19,代碼來源:reports.py

示例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}) 
開發者ID:agstrike,項目名稱:silverstrike,代碼行數:27,代碼來源:api.py


注:本文中的django.db.models.Sum方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。