Python django.db.models.Max() Examples

The following are 30 code examples for showing how to use django.db.models.Max(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module django.db.models , or try the search function .

Example 1
Project: figures   Author: appsembler   File: metrics.py    License: MIT License 6 votes vote down vote up
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 
Example 2
Project: figures   Author: appsembler   File: metrics.py    License: MIT License 6 votes vote down vote up
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 
Example 3
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
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() 
Example 4
Project: django-rest-messaging   Author: raphaelgyory   File: models.py    License: ISC License 6 votes vote down vote up
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 
Example 5
Project: django-idcops   Author: Wenvki   File: forms.py    License: Apache License 2.0 6 votes vote down vote up
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) 
Example 6
Project: koku   Author: project-koku   File: test_ocp_report_db_accessor.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example 7
Project: koku   Author: project-koku   File: test_ocp_report_db_accessor.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example 8
Project: koku   Author: project-koku   File: test_ocp_report_db_accessor.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example 9
Project: koku   Author: project-koku   File: test_ocp_report_db_accessor.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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()) 
Example 10
Project: koku   Author: project-koku   File: test_aws_report_db_accessor.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example 11
Project: anytask   Author: znick   File: models.py    License: MIT License 6 votes vote down vote up
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() 
Example 12
Project: timed-backend   Author: adfinis-sygroup   File: serializers.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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 
Example 13
Project: mangaki   Author: mangaki   File: 0088_auto_20171225_1534.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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… 
Example 14
Project: mangaki   Author: mangaki   File: work_merge.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
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) 
Example 15
Project: scale   Author: ngageoint   File: models.py    License: Apache License 2.0 6 votes vote down vote up
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 
Example 16
Project: figures   Author: appsembler   File: metrics.py    License: MIT License 5 votes vote down vote up
def get_total_site_users_for_time_period(site, start_date, end_date, **kwargs):
    """
    Returns the maximum number of users who joined before or on the end date

    Even though we don't need the start_date, we follow the method signature
    for the other metrics functions so we can use the same handler method,
    ``get_monthly_history_metric``

    TODO: Consider first trying to get the data from the SiteDailyMetrics
    model. If there are no records, then get the data from the User model
    """
    def calc_from_user_model():
        filter_args = dict(
            date_joined__lt=as_datetime(next_day(end_date)),
        )
        users = figures.sites.get_users_for_site(site)
        return users.filter(**filter_args).count()

    def calc_from_site_daily_metrics():
        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_user_count'))['maxval']
        else:
            return 0

    if kwargs.get('calc_from_sdm'):
        return calc_from_site_daily_metrics()
    else:
        return calc_from_user_model() 
Example 17
Project: figures   Author: appsembler   File: metrics.py    License: MIT License 5 votes vote down vote up
def get_total_site_courses_for_time_period(site, start_date, end_date, **kwargs):
    """
    Potential fix:
    get unique course ids from CourseEnrollment
    """
    def calc_from_site_daily_metrics():
        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('course_count'))['maxval']
        else:
            return 0

    def calc_from_course_enrollments():
        filter_args = dict(
            created__gt=prev_day(start_date),
            created__lt=next_day(end_date),
        )
        # First get all the course enrollments for the site
        ce = figures.sites.get_course_enrollments_for_site(site)
        # Then filter on the time period
        return ce.filter(
            **filter_args).values('course_id').distinct().count()

    if kwargs.get('calc_raw'):
        return calc_from_course_enrollments()
    else:
        return calc_from_site_daily_metrics() 
Example 18
Project: figures   Author: appsembler   File: metrics.py    License: MIT License 5 votes vote down vote up
def get_total_course_completions_for_time_period(site, start_date, end_date):
    """
    This metric is not currently captured in SiteDailyMetrics, so retrieving from
    course dailies instead
    """
    def calc_from_course_daily_metrics():
        filter_args = dict(
            site=site,
            date_for__gt=prev_day(start_date),
            date_for__lt=next_day(end_date),
        )
        qs = CourseDailyMetrics.objects.filter(**filter_args)
        if qs:
            return qs.aggregate(maxval=Max('num_learners_completed'))['maxval']
        else:
            return 0

    return calc_from_course_daily_metrics()


# -------------------------
# Course metrics collectors
# -------------------------
#
# TODO: move these to `figures.metrics.course` module
#
# TODO: Consider moving these aggregate queries to the
# CourseDailyMetricsManager class (not yet created) 
Example 19
def _get_transition_images(self, source_states):
        meta_max_iteration = Transition.objects.filter(
            workflow=self.workflow,
            workflow_object=self.workflow_object,
            source_state__pk__in=source_states,
        ).values_list("meta").annotate(max_iteration=Max("iteration"))

        return Transition.objects.filter(
            Q(workflow=self.workflow, object_id=self.workflow_object.pk) &
            six.moves.reduce(lambda agg, q: q | agg, [Q(meta__id=meta_id, iteration=max_iteration) for meta_id, max_iteration in meta_max_iteration], Q(pk=-1))
        ) 
Example 20
Project: donation-tracker   Author: GamesDoneQuick   File: public.py    License: Apache License 2.0 5 votes vote down vote up
def index(request, event=None):
    event = viewutil.get_event(event)
    eventParams = {}

    if event.id:
        eventParams['event'] = event.id

    agg = Donation.objects.filter(
        transactionstate='COMPLETED', testdonation=False, **eventParams
    ).aggregate(
        amount=Cast(Coalesce(Sum('amount'), 0), output_field=FloatField()),
        count=Count('amount'),
        max=Cast(Coalesce(Max('amount'), 0), output_field=FloatField()),
        avg=Cast(Coalesce(Avg('amount'), 0), output_field=FloatField()),
    )
    agg['target'] = float(event.targetamount)
    count = {
        'runs': filters.run_model_query('run', eventParams).count(),
        'prizes': filters.run_model_query('prize', eventParams).count(),
        'bids': filters.run_model_query('bid', eventParams).count(),
        'donors': filters.run_model_query('donorcache', eventParams)
        .values('donor')
        .distinct()
        .count(),
    }

    if 'json' in request.GET:
        return HttpResponse(
            json.dumps({'count': count, 'agg': agg}, ensure_ascii=False,),
            content_type='application/json;charset=utf-8',
        )

    return views_common.tracker_response(
        request, 'tracker/index.html', {'agg': agg, 'count': count, 'event': event}
    ) 
Example 21
Project: donation-tracker   Author: GamesDoneQuick   File: donation.py    License: Apache License 2.0 5 votes vote down vote up
def update(self):
        aggregate = Donation.objects.filter(
            donor=self.donor, transactionstate='COMPLETED'
        )
        if self.event:
            aggregate = aggregate.filter(event=self.event)
        aggregate = aggregate.aggregate(
            total=Coalesce(Sum('amount'), 0.0),
            count=Coalesce(Count('amount'), 0),
            max=Coalesce(Max('amount'), 0.0),
            avg=Coalesce(Avg('amount'), 0.0),
        )
        self.donation_total = aggregate['total']
        self.donation_count = aggregate['count']
        self.donation_max = aggregate['max']
        self.donation_avg = aggregate['avg'] 
Example 22
Project: wanggeService   Author: pchaos   File: freshhigh.py    License: MIT License 5 votes vote down vote up
def updateHigh(cls, code, entries):
        h = l = 0
        for v in entries:
            if h == 0:
                # 第一条记录,查询时候有历史数据
                ld = cls.objects.all().filter(code=code).aggregate(Max("ltradedate"))['ltradedate__max']
                qs = cls.objects.all().filter(code=code, ltradedate=ld)
                if qs.count() > 0:
                    # 有历史数据
                    val = qs.values().first()
                    l = val['low']
                    h = val['high']
                    hd = val['htradedate']
                    # cls.update(code, val['high'], val['htradedate'],l, v['date'])

            if h < v['high']:
                if h > 0 and l > v['low']:
                    # 不是第一次保存,并且最低价不是最后的最低价 (可能会出现新高以后再出现最低价,这个情况暂不考虑)
                    cls.update(code, h, hd, l, v['date'])
                h = v['high']
                l = v['close']
                hd = v['date']
                _, created = cls.objects.get_or_create(code=code, high=h, low=l, htradedate=v['date'],
                                                       ltradedate=v['date'])
            else:
                if l > v['low']:
                    l = v['low']
                    cls.update(code, h, hd, l, v['date']) 
Example 23
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def question_reorder(request: HttpRequest, course_slug: str, activity_slug: str, question_id: str) -> HttpResponse:
    quiz = get_object_or_404(Quiz, activity__slug=activity_slug, activity__offering__slug=course_slug)
    question1 = get_object_or_404(Question, quiz=quiz, id=question_id)

    direction = request.GET.get('direction', '')
    if direction not in ['up', 'down']:
        raise Http404()

    #if quiz.completed():
    #    return ForbiddenResponse(request, 'Quiz is completed. You cannot modify questions after the end of the quiz time')

    try:
        if direction == 'up':
            # find question before this one
            prev_order = Question.objects.filter(quiz=quiz, order__lt=question1.order).aggregate(Max('order'))['order__max']
            question2 = Question.objects.get(quiz=quiz, order=prev_order)
        else:
            # find question after this one
            next_order = Question.objects.filter(quiz=quiz, order__gt=question1.order).aggregate(Min('order'))['order__min']
            question2 = Question.objects.get(quiz=quiz, order=next_order)

    except Question.DoesNotExist:
        # moving up past the start, or down past the end: ignore
        pass

    else:
        o1 = question1.order
        o2 = question2.order
        with transaction.atomic():
            question2.order = o1
            question2.save()
            question1.order = o2
            question1.save()
            if quiz.activity.quiz_marking():
                # configured for quiz-based marking: update that so the order matches
                quiz.configure_marking(delete_others=False)
                messages.add_message(request, messages.INFO, 'Reordered marking rubric to match quiz questions.')

    return HttpResponseRedirect(resolve_url('offering:quiz:index', course_slug=course_slug, activity_slug=activity_slug)
                                + '#q-' + str(question1.id)) 
Example 24
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def set_order(self):
        """
        If the question has no .order, set the .order value to the current max + 1
        """
        if self.order is not None:
            return

        current_max = Question.objects.filter(quiz=self.quiz).aggregate(Max('order'))['order__max']
        if not current_max:
            self.order = 1
        else:
            self.order = current_max + 1 
Example 25
Project: coursys   Author: sfu-fas   File: base.py    License: GNU General Public License v3.0 5 votes vote down vote up
def save(self, **kwargs):
        if self.position is None:
            lastpos = SubmissionComponent.objects.filter(activity=self.activity) \
                    .aggregate(Max('position'))['position__max']
            if lastpos is None:
                lastpos = 0
            self.position = lastpos+1
        super(SubmissionComponent, self).save(**kwargs)




# per-submission models, created when a student/group submits an assignment: 
Example 26
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def admin_list_all(request):
    admin = get_object_or_404(Person, userid=request.user.username)
    form_groups = FormGroup.objects.filter(members=admin)
    if form_groups:
        pend_submissions = FormSubmission.objects.filter(owner__in=form_groups, status='PEND') \
                .annotate(last_sheet_dt=Max('sheetsubmission__completed_at')) \
                .select_related('initiator__sfuFormFiller', 'initiator__nonSFUFormFiller', 'form')

        #Waiting submissions
        wait_submissions = list(FormSubmission.objects.filter(owner__in=form_groups, status='WAIT') \
                .select_related('initiator__sfuFormFiller', 'initiator__nonSFUFormFiller', 'form'))
        wait_lookup = dict((fs.id, fs) for fs in wait_submissions)
        wait_ss = SheetSubmission.objects.filter(form_submission__in=wait_submissions).order_by('given_at') \
                .select_related('filler__sfuFormFiller', 'filler__nonSFUFormFiller', 'sheet')

        # .assigned_to will be the most recently given_at sheetsub after this
        for ss in wait_ss:
            wait_lookup[ss.form_submission_id].assigned_to = ss
            # We no longer allow returning/assigning the initial sheet.  Let's find out if the sheet that is waiting
            # is the initial sheet, as this would indicate an unsubmitted form.  We should display that in a separate
            # list.  However, the initial sheet can have been assigned manually via the "Assign a form" link.  In those
            # cases, treat it as a normal Waiting form.  The cleanup tasks will also not delete those after 14 days.
            wait_lookup[ss.form_submission_id].is_initial = ss.sheet.is_initial and not ss.assigner()
        #  Let's split up the list between unsubmitted forms and submitted ones.  Most people won't care about the
        # unsubmitted ones.
        unsubmitted_forms = [f for f in wait_submissions if f.is_initial]
        wait_submissions = [f for f in wait_submissions if not f.is_initial]

    # Create a quick summary of pending forms to easily see at the top of the page so one doesn't have to scroll
    # through the whole table to see what needs to be worked on.
    submission_summary = {}
    if pend_submissions:
        for s in pend_submissions:
            if s.form.title in submission_summary:
                submission_summary[s.form.title] += 1
            else:
                submission_summary[s.form.title] = 1
    sub_summary = sorted(submission_summary.items(), key=lambda x: x[1], reverse=True)
    context = {'pend_submissions': pend_submissions, 'wait_submissions': wait_submissions,
               'unsubmitted_forms': unsubmitted_forms, 'sub_summary': sub_summary}
    return render(request, "onlineforms/admin/admin_forms.html", context) 
Example 27
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def admin_completed_form(request, form_slug):
    form = get_object_or_404(Form, slug=form_slug, owner__in=request.formgroups)
    formsubs = FormSubmission.objects.filter(form=form, status='DONE') \
           .select_related('initiator__sfuFormFiller', 'initiator__nonSFUFormFiller') \
           .annotate(last_sheet_dt=Max('sheetsubmission__completed_at'))

    context = {'form': form, 'formsubs': formsubs}
    return render(request, "onlineforms/admin/admin_completed_form.html", context) 
Example 28
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def save(self, *args, **kwargs):
        with django.db.transaction.atomic():
            # if this field is just being created it needs a order number
            if(self.order == None):
                max_aggregate = Field.objects.filter(sheet=self.sheet).aggregate(Max('order'))
                if(max_aggregate['order__max'] == None):
                    next_order = 0
                else:
                    next_order = max_aggregate['order__max'] + 1
                self.order = next_order


            super(Field, self).save(*args, **kwargs)
            self.cleanup_fields() 
Example 29
Project: coursys   Author: sfu-fas   File: models.py    License: GNU General Public License v3.0 5 votes vote down vote up
def last_sheet_completion(self):
        if hasattr(self, 'last_sheet_dt'):
            # use the one annotated in here by .annotate(last_sheet_dt=Max('sheetsubmission__completed_at'))
            return self.last_sheet_dt

        # In the case of closed forms, we probably care about when the form was actually closed. Finding the last
        # FormLogEntry with category 'ADMN' should hopefully tell us that.
        if self.status == 'DONE' and self.formlogentry_set.filter(category='ADMN').count() > 0:
            return self.formlogentry_set.filter(category='ADMN').last().timestamp

        return self.sheetsubmission_set.all().aggregate(Max('completed_at'))['completed_at__max'] 
Example 30
Project: coursys   Author: sfu-fas   File: views.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _new_fake_class_nbr(semester):
    # largest class_nbr in production is 47348. Assuming that >65536 can be reserved as fakes.
    from django.db.models import Max
    max_offering = CourseOffering.objects.filter(semester=semester).aggregate(Max('class_nbr'))['class_nbr__max']
    max_combined = CombinedOffering.objects.filter(semester=semester).aggregate(Max('class_nbr'))['class_nbr__max']

    nbr = 65536
    if max_offering:
        nbr = max(nbr, max_offering)
    if max_combined:
        nbr = max(nbr, max_combined)

    return nbr+1