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


Python models.Max方法代碼示例

本文整理匯總了Python中django.db.models.Max方法的典型用法代碼示例。如果您正苦於以下問題:Python models.Max方法的具體用法?Python models.Max怎麽用?Python models.Max使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在django.db.models的用法示例。


在下文中一共展示了models.Max方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: get_total_enrollments_for_time_period

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Max [as 別名]
def get_total_enrollments_for_time_period(site, start_date, end_date,
                                          course_ids=None):  # pylint: disable=unused-argument
    """Returns the maximum number of enrollments

    This returns the count of unique enrollments, not unique learners
    """
    filter_args = dict(
        site=site,
        date_for__gt=prev_day(start_date),
        date_for__lt=next_day(end_date),
    )

    qs = SiteDailyMetrics.objects.filter(**filter_args)
    if qs:
        return qs.aggregate(maxval=Max('total_enrollment_count'))['maxval']
    else:
        return 0 
開發者ID:appsembler,項目名稱:figures,代碼行數:19,代碼來源:metrics.py

示例2: get_course_enrolled_users_for_time_period

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Max [as 別名]
def get_course_enrolled_users_for_time_period(site, start_date, end_date, course_id):
    """

    """
    filter_args = dict(
        site=site,
        date_for__gt=prev_day(start_date),
        date_for__lt=next_day(end_date),
        course_id=course_id
    )

    qs = CourseDailyMetrics.objects.filter(**filter_args)
    if qs:
        return qs.aggregate(maxval=Max('enrollment_count'))['maxval']
    else:
        return 0 
開發者ID:appsembler,項目名稱:figures,代碼行數:18,代碼來源:metrics.py

示例3: save

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Max [as 別名]
def save(self, *args, **kwargs):
        with django.db.transaction.atomic():
            # if this sheet is just being created it needs a order number
            if(self.order == None):
                max_aggregate = Sheet.objects.filter(form=self.form).aggregate(Max('order'))
                if(max_aggregate['order__max'] == None):
                    next_order = 0
                    # making first sheet for form--- initial 
                    self.is_initial = True
                else:
                    next_order = max_aggregate['order__max'] + 1
                self.order = next_order

            #assert (self.is_initial and self.order==0) or (not self.is_initial and self.order>0)
      
            super(Sheet, self).save(*args, **kwargs)
            self.cleanup_fields() 
開發者ID:sfu-fas,項目名稱:coursys,代碼行數:19,代碼來源:models.py

示例4: get_lasts_messages_of_threads

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Max [as 別名]
def get_lasts_messages_of_threads(self, participant_id, check_who_read=True, check_is_notification=True):
        """ Returns the last message in each thread """
        # we get the last message for each thread
        # we must query the messages using two queries because only Postgres supports .order_by('thread', '-sent_at').distinct('thread')
        threads = Thread.managers.\
            get_threads_where_participant_is_active(participant_id).\
            annotate(last_message_id=Max('message__id'))
        messages = Message.objects.filter(id__in=[thread.last_message_id for thread in threads]).\
            order_by('-id').\
            distinct().\
            select_related('thread', 'sender')

        if check_who_read is True:
            messages = messages.prefetch_related('thread__participation_set', 'thread__participation_set__participant')
            messages = self.check_who_read(messages)
        else:
            messages = messages.prefetch_related('thread__participants')

        if check_is_notification is True:
            messages = self.check_is_notification(participant_id, messages)
        return messages 
開發者ID:raphaelgyory,項目名稱:django-rest-messaging,代碼行數:23,代碼來源:models.py

示例5: __init__

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Max [as 別名]
def __init__(self, *args, **kwargs):
        self.zone_id = kwargs.pop('zone_id', None)
        super(ZonemapNewForm, self).__init__(*args, **kwargs)
        if self.zone_id is not None:
            from django.db.models import Max
            from idcops.models import Zonemap
            cells = Zonemap.objects.filter(zone_id=self.zone_id).order_by(
                "row", "col").values("row", "col")
            if cells.exists():
                LAST_ROWS = cells.aggregate(Max('row'))['row__max']
                LAST_COLS = cells.aggregate(Max('col'))['col__max']
            else:
                LAST_ROWS = LAST_COLS = 0
            self.fields['zone_id'].initial = self.zone_id
            self.fields['rows'].initial = LAST_ROWS + 1
            self.fields['cols'].initial = LAST_COLS + 1
            self.fields['rows'].help_text = "類似Excel表格,行列從0開始標記,當前已有 %s行" % (
                LAST_ROWS+1)
            self.fields['cols'].help_text = "類似Excel表格,行列從0開始標記,當前已有 %s列" % (
                LAST_COLS+1) 
開發者ID:Wenvki,項目名稱:django-idcops,代碼行數:22,代碼來源:forms.py

示例6: _populate_storage_summary

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Max [as 別名]
def _populate_storage_summary(self, cluster_id=None):
        """Generate storage summary data."""
        report_table_name = OCP_REPORT_TABLE_MAP["report"]
        report_table = getattr(self.accessor.report_schema, report_table_name)
        if cluster_id is None:
            cluster_id = self.cluster_id
        for _ in range(25):
            pod = "".join(random.choice(string.ascii_lowercase) for _ in range(10))
            namespace = "".join(random.choice(string.ascii_lowercase) for _ in range(10))
            self.creator.create_ocp_usage_line_item(self.reporting_period, self.report, pod=pod, namespace=namespace)
            self.creator.create_ocp_storage_line_item(self.reporting_period, self.report, pod=pod, namespace=namespace)
        self.creator.create_ocp_node_label_line_item(self.reporting_period, self.report)
        with schema_context(self.schema):
            report_entry = report_table.objects.all().aggregate(Min("interval_start"), Max("interval_start"))
            start_date = report_entry["interval_start__min"]
            end_date = report_entry["interval_start__max"]

        start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0)
        end_date = end_date.replace(hour=0, minute=0, second=0, microsecond=0)

        self.accessor.populate_node_label_line_item_daily_table(start_date, end_date, cluster_id)
        self.accessor.populate_line_item_daily_table(start_date, end_date, cluster_id)

        self.accessor.populate_storage_line_item_daily_table(start_date, end_date, cluster_id)
        self.accessor.populate_storage_line_item_daily_summary_table(start_date, end_date, cluster_id) 
開發者ID:project-koku,項目名稱:koku,代碼行數:27,代碼來源:test_ocp_report_db_accessor.py

示例7: _populate_pod_summary

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Max [as 別名]
def _populate_pod_summary(self):
        """Generate pod summary data."""
        report_table_name = OCP_REPORT_TABLE_MAP["report"]
        report_table = getattr(self.accessor.report_schema, report_table_name)

        cluster_id = "testcluster"
        for _ in range(25):
            self.creator.create_ocp_usage_line_item(self.reporting_period, self.report)

        self.creator.create_ocp_node_label_line_item(self.reporting_period, self.report)
        with schema_context(self.schema):
            report_entry = report_table.objects.all().aggregate(Min("interval_start"), Max("interval_start"))
            start_date = report_entry["interval_start__min"]
            end_date = report_entry["interval_start__max"]

        start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0)
        end_date = end_date.replace(hour=0, minute=0, second=0, microsecond=0)

        self.accessor.populate_node_label_line_item_daily_table(start_date, end_date, cluster_id)
        self.accessor.populate_line_item_daily_table(start_date, end_date, cluster_id)
        self.accessor.populate_line_item_daily_summary_table(start_date, end_date, cluster_id)
        return (start_date, end_date) 
開發者ID:project-koku,項目名稱:koku,代碼行數:24,代碼來源:test_ocp_report_db_accessor.py

示例8: test_upsert_monthly_cluster_cost_line_item

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Max [as 別名]
def test_upsert_monthly_cluster_cost_line_item(self):
        """Test that the cluster monthly costs are not updated."""
        report_table_name = OCP_REPORT_TABLE_MAP["report"]
        report_table = getattr(self.accessor.report_schema, report_table_name)
        rate = 1000
        with schema_context(self.schema):
            report_entry = report_table.objects.all().aggregate(Min("interval_start"), Max("interval_start"))
            start_date = report_entry["interval_start__min"]
            end_date = report_entry["interval_start__max"]

            start_date = str(self.reporting_period.report_period_start)
            end_date = str(self.reporting_period.report_period_end)
            self.accessor.upsert_monthly_cluster_cost_line_item(
                start_date, end_date, self.cluster_id, "cluster_alias", metric_constants.SUPPLEMENTARY_COST_TYPE, rate
            )
            summary_table_name = OCP_REPORT_TABLE_MAP["line_item_daily_summary"]
            query = self.accessor._get_db_obj_query(summary_table_name)
            self.assertEqual(query.filter(cluster_id=self.cluster_id).first().supplementary_monthly_cost, rate) 
開發者ID:project-koku,項目名稱:koku,代碼行數:20,代碼來源:test_ocp_report_db_accessor.py

示例9: test_upsert_monthly_cluster_cost_line_item_no_report_period

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Max [as 別名]
def test_upsert_monthly_cluster_cost_line_item_no_report_period(self):
        """Test that the cluster monthly costs are not updated when no report period  is found."""
        report_table_name = OCP_REPORT_TABLE_MAP["report"]
        report_table = getattr(self.accessor.report_schema, report_table_name)
        rate = 1000

        with schema_context(self.schema):
            report_entry = report_table.objects.all().aggregate(Min("interval_start"), Max("interval_start"))
            start_date = report_entry["interval_start__min"]
            end_date = report_entry["interval_start__max"]

            start_date = start_date.replace(hour=0, minute=0, second=0, microsecond=0)
            end_date = end_date.replace(hour=0, minute=0, second=0, microsecond=0)
            self.accessor.upsert_monthly_cluster_cost_line_item(
                start_date, end_date, self.cluster_id, "cluster_alias", metric_constants.SUPPLEMENTARY_COST_TYPE, rate
            )
            summary_table_name = OCP_REPORT_TABLE_MAP["line_item_daily_summary"]
            query = self.accessor._get_db_obj_query(summary_table_name)
            self.assertFalse(query.filter(cluster_id=self.cluster_id).exists()) 
開發者ID:project-koku,項目名稱:koku,代碼行數:21,代碼來源:test_ocp_report_db_accessor.py

示例10: test_populate_markup_cost_no_billsids

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Max [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

示例11: set_position_in_new_group

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Max [as 別名]
def set_position_in_new_group(self, groups=None):
        if not groups:
            groups = self.course.groups.all()
        else:
            for task_related in TaskGroupRelations.objects.filter(task=self).exclude(group__in=groups):
                task_related.deleted = True
                task_related.save()

        for group in list(groups):
            task_related, created = TaskGroupRelations.objects.get_or_create(task=self, group=group)

            if created:
                max_position = TaskGroupRelations.objects.filter(group=group).exclude(id=task_related.id) \
                    .aggregate(Max('position'))['position__max']
                task_related.position = max_position + 1 if max_position is not None else 0
            else:
                task_related.deleted = False
            task_related.save() 
開發者ID:znick,項目名稱:anytask,代碼行數:20,代碼來源:models.py

示例12: get_date

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Max [as 別名]
def get_date(self, instance):
        user = instance.id
        today = date.today()

        if instance.date is not None:
            return instance.date

        # calculate last reported day if no specific date is set
        max_absence_date = Absence.objects.filter(user=user, date__lt=today).aggregate(
            date=Max("date")
        )
        max_report_date = Report.objects.filter(user=user, date__lt=today).aggregate(
            date=Max("date")
        )

        last_reported_date = max(
            max_absence_date["date"] or date.min, max_report_date["date"] or date.min
        )

        instance.date = last_reported_date
        return instance.date 
開發者ID:adfinis-sygroup,項目名稱:timed-backend,代碼行數:23,代碼來源:serializers.py

示例13: remove_duplicates

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Max [as 別名]
def remove_duplicates(apps, schema_editor):
    Reference = apps.get_model('mangaki', 'Reference')
    db_alias = schema_editor.connection.alias

    unique_fields = ['work', 'source', 'identifier']

    duplicates = (Reference.objects.using(db_alias)
                                   .values(*unique_fields)
                                   .order_by()
                                   .annotate(max_id=models.Max('id'),
                                             count_id=models.Count('id'))
                                   .filter(count_id__gt=1)
                                   .iterator())

    for duplicate in duplicates:
        (Reference.objects.using(db_alias)
                          .filter(**{x: duplicate[x] for x in unique_fields})
                          .exclude(id=duplicate['max_id'])
                          .delete())

# migrations.RunPython.noop cause circular reference error… 
開發者ID:mangaki,項目名稱:mangaki,代碼行數:23,代碼來源:0088_auto_20171225_1534.py

示例14: redirect_ratings

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Max [as 別名]
def redirect_ratings(self):
        # Get all IDs of considered ratings
        get_id_of_rating = {}
        for rating_id, user_id, date in Rating.objects.filter(work__in=self.works_to_merge).values_list('id', 'user_id',
                                                                                                        'date'):
            get_id_of_rating[(user_id, date)] = rating_id
        # What is the latest rating of every user? (N. B. – latest may be null)
        kept_rating_ids = []
        latest_ratings = (Rating.objects.filter(
            work__in=self.works_to_merge
        ).values('user_id').annotate(latest=Max('date')))
        for rating in latest_ratings:
            user_id = rating['user_id']
            date = rating['latest']
            kept_rating_ids.append(get_id_of_rating[(user_id, date)])
        Rating.objects.filter(work__in=self.works_to_merge).exclude(id__in=kept_rating_ids).delete()
        Rating.objects.filter(id__in=kept_rating_ids).update(work_id=self.target_work.id) 
開發者ID:mangaki,項目名稱:mangaki,代碼行數:19,代碼來源:work_merge.py

示例15: get_performance

# 需要導入模塊: from django.db import models [as 別名]
# 或者: from django.db.models import Max [as 別名]
def get_performance(self, job_type_id, started, ended=None):
        """Returns the job count statistics for a given job type and time range.

        :param job_type_id: The unique identifier of the job type.
        :type job_type_id: int
        :param started: Query job types updated after this amount of time.
        :type started: :class:`datetime.datetime`
        :param ended: Query job types updated before this amount of time.
        :type ended: :class:`datetime.datetime`
        :returns: A list of job counts organized by status.
        :rtype: [:class:`job.models.JobTypeStatusCounts`]
        """
        count_dicts = Job.objects.values('job_type__id', 'status', 'error__category')
        count_dicts = count_dicts.filter(job_type_id=job_type_id, last_status_change__gte=started)
        if ended:
            count_dicts = count_dicts.filter(last_status_change__lte=ended)
        count_dicts = count_dicts.annotate(count=models.Count('job_type'),
                                           most_recent=models.Max('last_status_change'))
        results = []
        for count_dict in count_dicts:
            counts = JobTypeStatusCounts(count_dict['status'], count_dict['count'],
                                         count_dict['most_recent'], count_dict['error__category'])
            results.append(counts)
        return results 
開發者ID:ngageoint,項目名稱:scale,代碼行數:26,代碼來源:models.py


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