Python django.db.models.OuterRef() Examples

The following are 30 code examples of django.db.models.OuterRef(). 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 also want to check out all available functions/classes of the module django.db.models , or try the search function .
Example #1
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_orders_nulls_first_on_filtered_subquery(self):
        Article.objects.filter(headline='Article 1').update(author=self.author_1)
        Article.objects.filter(headline='Article 2').update(author=self.author_1)
        Article.objects.filter(headline='Article 4').update(author=self.author_2)
        Author.objects.filter(name__isnull=True).delete()
        author_3 = Author.objects.create(name='Name 3')
        article_subquery = Article.objects.filter(
            author=OuterRef('pk'),
            headline__icontains='Article',
        ).order_by().values('author').annotate(
            last_date=Max('pub_date'),
        ).values('last_date')
        self.assertQuerysetEqualReversible(
            Author.objects.annotate(
                last_date=Subquery(article_subquery, output_field=DateTimeField())
            ).order_by(
                F('last_date').asc(nulls_first=True)
            ).distinct(),
            [author_3, self.author_1, self.author_2],
        ) 
Example #2
Source File: tests.py    From djongo with GNU Affero General Public License v3.0 6 votes vote down vote up
def test_orders_nulls_first_on_filtered_subquery(self):
        Article.objects.filter(headline='Article 1').update(author=self.author_1)
        Article.objects.filter(headline='Article 2').update(author=self.author_1)
        Article.objects.filter(headline='Article 4').update(author=self.author_2)
        Author.objects.filter(name__isnull=True).delete()
        author_3 = Author.objects.create(name='Name 3')
        article_subquery = Article.objects.filter(
            author=OuterRef('pk'),
            headline__icontains='Article',
        ).order_by().values('author').annotate(
            last_date=Max('pub_date'),
        ).values('last_date')
        self.assertQuerysetEqualReversible(
            Author.objects.annotate(
                last_date=Subquery(article_subquery, output_field=DateTimeField())
            ).order_by(
                F('last_date').asc(nulls_first=True)
            ).distinct(),
            [author_3, self.author_1, self.author_2],
        ) 
Example #3
Source File: module_registry.py    From cjworkbench with GNU Affero General Public License v3.0 6 votes vote down vote up
def all_latest(self) -> Dict[str, ModuleZipfile]:
        """
        Return all modules, unordered, indexed by ID.
        """
        # https://docs.djangoproject.com/en/2.2/ref/models/expressions/#subquery-expressions
        latest = Subquery(
            (
                DbModuleVersion.objects.filter(id_name=OuterRef("id_name"))
                .order_by("-last_update_time")
                .values("id")
            )[:1]
        )
        db_modules = list(
            DbModuleVersion.objects.annotate(_latest=latest).filter(id=F("_latest"))
        )

        ret = dict(StaticModuleLookup)  # fallback modules (TODO nix all static modules)
        ret.update({m.id_name: self._download_or_reuse_zipfile(m) for m in db_modules})
        return ret 
Example #4
Source File: views.py    From dj4e-samples with MIT License 6 votes vote down vote up
def get(self, request) :
        if not request.user.is_authenticated:
            thing_list = Thing.objects.all()
        else:
            thing_list = Thing.objects.annotate(
                FAV_USER_ID=Exists(Fav.objects.filter(user=self.request.user,thing_id=OuterRef('id')))
                ).all()
        ctx = {'thing_list' : thing_list}
        return render(request, self.template_name, ctx)

# https://stackoverflow.com/questions/2314920/django-show-log-orm-sql-calls-from-python-shell
# pip install django-extensions
# ./manage.py shell_plus --print-sql

# Below this line, we see raw sql...   With great power comes great responsibility
# https://docs.djangoproject.com/en/3.0/topics/db/sql/

# A List view using raw SQL - super efficient 
Example #5
Source File: views.py    From pythonic-news with GNU Affero General Public License v3.0 6 votes vote down vote up
def threads(request):
    page = int(request.GET.get('p', 0))
    paging_size = settings.PAGING_SIZE
    tree = Comment.objects.filter( tree_id=OuterRef('tree_id'), user=OuterRef('user')).values('tree_id', 'user__pk').annotate(min_level=Min('level')).order_by()
    stories = Comment.objects.filter(
        user=request.user
    ).filter(
        Q(level__in=Subquery(tree.values('min_level'), output_field=models.IntegerField()))  # TODO: level= or level__in= ???
    ).select_related(
        'user', 'parent', 'to_story'
    ).order_by(
        '-created_at'
    )[(page*paging_size):(page+1)*(paging_size)]
    if len(stories) < 1 and page != 0:
        back = _one_page_back(request)
        if back:
            return back
    return render(request, 'news/index.html', {'stories': stories, 'hide_text':False, 'page': page, 'rank_start': None, 'show_children': True}) 
Example #6
Source File: views.py    From arxiv-vanity with Apache License 2.0 5 votes vote down vote up
def stats(request):
    past_30_days = Render.objects.filter(
        created_at__gt=datetime.datetime.today() - datetime.timedelta(days=30)
    )

    newest_renders = Render.objects.filter(paper=OuterRef("pk")).order_by("-created_at")
    papers = Paper.objects.annotate(
        last_render_state=Subquery(newest_renders.values("state")[:1])
    ).exclude(last_render_state=None)

    return render(
        request,
        "papers/stats.html",
        {
            "total_renders": int(Render.objects.count()),
            "successful_renders": int(
                Render.objects.filter(state=Render.STATE_SUCCESS).count()
            ),
            "failed_renders": int(
                Render.objects.filter(state=Render.STATE_FAILURE).count()
            ),
            "total_renders_30_days": int(past_30_days.count()),
            "successful_renders_30_days": int(
                past_30_days.filter(state=Render.STATE_SUCCESS).count()
            ),
            "failed_renders_30_days": int(
                past_30_days.filter(state=Render.STATE_FAILURE).count()
            ),
            "total_papers": int(papers.count()),
            "successful_papers": int(
                papers.filter(last_render_state=Render.STATE_SUCCESS).count()
            ),
            "failed_papers": int(
                papers.filter(last_render_state=Render.STATE_FAILURE).count()
            ),
        },
    ) 
Example #7
Source File: filters.py    From caluma with GNU General Public License v3.0 5 votes vote down vote up
def filter_order_by_question_answer_value(queryset, _, question_slug):
        order_by = "-order_value" if question_slug.startswith("-") else "order_value"
        question_slug = question_slug.lstrip("-")

        # Based on question type, set answer field to use for sorting
        not_supported = (Question.TYPE_TABLE,)
        question = Question.objects.get(slug=question_slug)
        answer_value = "value"
        if question.type in not_supported:
            raise RuntimeError(
                f'Questions with type "{question.type}" are not supported '
                f'by "filterOrderByQuestionAnswerValue"'
            )
        elif question.type == Question.TYPE_DATE:
            answer_value = "date"
        elif question.type == Question.TYPE_FILE:
            answer_value = "file__name"

        # Initialize subquery
        answers = Answer.objects.filter(
            question=question, document=OuterRef("document")
        )

        # Annotate the cases in the queryset with the value of the answer of the given
        # question and order by it.
        return queryset.annotate(
            order_value=Subquery(answers.values(answer_value)[:1])
        ).order_by(order_by) 
Example #8
Source File: ordering.py    From caluma with GNU General Public License v3.0 5 votes vote down vote up
def get_ordering_value(
        self, qs: QuerySet, value: Any
    ) -> Tuple[QuerySet, OrderingFieldType]:
        # First, join the requested answer, then annotate the QS accordingly.
        # Last, return a field corresponding to the value
        #
        question = Question.objects.get(pk=value)
        QUESTION_TYPE_TO_FIELD = {
            Question.TYPE_INTEGER: "value",
            Question.TYPE_FLOAT: "value",
            Question.TYPE_DATE: "date",
            Question.TYPE_CHOICE: "value",
            Question.TYPE_TEXTAREA: "value",
            Question.TYPE_TEXT: "value",
            Question.TYPE_FILE: "file",
            Question.TYPE_DYNAMIC_CHOICE: "value",
            Question.TYPE_STATIC: "value",
        }

        try:
            value_field = QUESTION_TYPE_TO_FIELD[question.type]
        except KeyError:  # pragma: no cover
            raise exceptions.ValidationError(
                f"Question '{question.slug}' has unsupported type {question.type} for ordering"
            )

        answers_subquery = Subquery(
            Answer.objects.filter(
                question=question,
                document=OuterRef(f"{self._document_locator_prefix}pk"),
            ).values(value_field)
        )
        ann_name = f"order_{value}"

        qs = qs.annotate(**{ann_name: answers_subquery})

        # TODO: respect document_via
        return qs, F(ann_name) 
Example #9
Source File: test_qs_combinators.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_union_with_values_list_on_annotated_and_unannotated(self):
        ReservedName.objects.create(name='rn1', order=1)
        qs1 = Number.objects.annotate(
            has_reserved_name=Exists(ReservedName.objects.filter(order=OuterRef('num')))
        ).filter(has_reserved_name=True)
        qs2 = Number.objects.filter(num=9)
        self.assertCountEqual(qs1.union(qs2).values_list('num', flat=True), [1, 9]) 
Example #10
Source File: test_qs_combinators.py    From djongo with GNU Affero General Public License v3.0 5 votes vote down vote up
def test_union_with_values_list_on_annotated_and_unannotated(self):
        ReservedName.objects.create(name='rn1', order=1)
        qs1 = Number.objects.annotate(
            has_reserved_name=Exists(ReservedName.objects.filter(order=OuterRef('num')))
        ).filter(has_reserved_name=True)
        qs2 = Number.objects.filter(num=9)
        self.assertCountEqual(qs1.union(qs2).values_list('num', flat=True), [1, 9]) 
Example #11
Source File: 0050_auto_20190408_1301.py    From silver with Apache License 2.0 5 votes vote down vote up
def populate_billing_log_invoice_from_proforma(apps, schema_editor):
    db_alias = schema_editor.connection.alias

    BillingLog = apps.get_model('silver', 'BillingLog')
    Proforma = apps.get_model('silver', 'Proforma')

    BillingLog.objects.using(db_alias) \
        .filter(invoice=None) \
        .update(
            invoice_id=Subquery(
                Proforma.objects.using(db_alias)
                .filter(id=OuterRef('proforma_id'))
                .values('related_document_id')[:1]
            )
        ) 
Example #12
Source File: asset.py    From kpi with GNU Affero General Public License v3.0 5 votes vote down vote up
def deployed(self):
        """
        Filter for deployed assets (i.e. assets having at least one deployed
        version) in an efficient way that doesn't involve joining or counting.
        https://docs.djangoproject.com/en/2.2/ref/models/expressions/#django.db.models.Exists
        """
        deployed_versions = AssetVersion.objects.filter(
            asset=OuterRef('pk'), deployed=True
        )
        return self.annotate(deployed=Exists(deployed_versions)).filter(
            deployed=True
        ) 
Example #13
Source File: 0011_auto_20181124_2320.py    From Spirit with MIT License 5 votes vote down vote up
def populate_nickname(apps, schema_editor):
    from django.db.models import Subquery, OuterRef
    from ...core.conf import settings
    User = apps.get_model(settings.AUTH_USER_MODEL)
    UserProfile = apps.get_model("spirit_user", "UserProfile")
    first_user = UserProfile.objects.first()
    if first_user and not first_user.nickname:
        UserProfile.objects.all().update(
            nickname=Subquery(
                User.objects
                .filter(pk=OuterRef('user_id'))
                .values('username')[:1])) 
Example #14
Source File: models.py    From arxiv-vanity with Apache License 2.0 5 votes vote down vote up
def _with_has_not_deleted_render_annotation(self):
        renders = Render.objects.filter(paper=models.OuterRef("pk"), is_deleted=False)
        return self.annotate(has_not_deleted_render=models.Exists(renders)) 
Example #15
Source File: models.py    From arxiv-vanity with Apache License 2.0 5 votes vote down vote up
def _with_has_successful_render_annotation(self):
        renders = Render.objects.filter(
            paper=models.OuterRef("pk"), state=Render.STATE_SUCCESS
        )
        return self.annotate(has_successful_render=models.Exists(renders)) 
Example #16
Source File: models.py    From timed-backend with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_queryset(self):
        from timed.employment.models import PublicHoliday

        queryset = super().get_queryset()
        queryset = queryset.exclude(
            date__in=models.Subquery(
                PublicHoliday.objects.filter(
                    location__employments__user=models.OuterRef("user")
                ).values("date")
            )
        )
        return queryset 
Example #17
Source File: diff.py    From patchew with MIT License 5 votes vote down vote up
def _get_series_for_diff(self, q):
        def _get_message_data(m):
            filtered = ""
            sep = ""
            for l in m.get_body().splitlines():
                for pat, repl in [
                    (r"^index [0-9a-f]+\.\.[0-9a-f]+", r"index XXXXXXX..XXXXXXX"),
                    (
                        r"^@@ -[0-9]+,[0-9]+ \+[0-9]+,[0-9]+ @@( |$)",
                        r"@@ -XXX,XX +XXX,XX @@\1",
                    ),
                ]:
                    l = re.sub(pat, repl, l)
                filtered += sep + l
                sep = "\n"

            return PatchInfo(
                subject=m.subject,
                link=m.get_message_view_url(),
                has_replies=m.has_replies,
                body=filtered,
            )

        def _add_has_replies(q, **kwargs):
            replies = Message.objects.filter(
                in_reply_to=OuterRef("message_id"), **kwargs
            )
            return q.annotate(has_replies=Exists(replies))

        q = _add_has_replies(q, is_patch=False)
        s = q.first()

        ret = list()
        data = _get_message_data(s)
        ret.append(data)
        if not s.is_patch:
            for p in _add_has_replies(s.get_patches()):
                data = _get_message_data(p)
                ret.append(data)
        return ret 
Example #18
Source File: views.py    From patchew with MIT License 5 votes vote down vote up
def prepare_patches(request, m, max_depth=None):
    if m.total_patches == 1:
        return []
    replies = m.get_replies().filter(is_patch=True)
    commit_replies = api.models.Message.objects.filter(
        in_reply_to=OuterRef("message_id")
    )
    replies = replies.annotate(has_replies=Exists(commit_replies))
    project = m.project
    return [prepare_message(request, project, x, True) for x in replies] 
Example #19
Source File: legacy_ioi.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def update_participation(self, participation):
        cumtime = 0
        score = 0
        format_data = {}

        queryset = (participation.submissions.values('problem_id')
                                             .filter(points=Subquery(
                                                 participation.submissions.filter(problem_id=OuterRef('problem_id'))
                                                                          .order_by('-points').values('points')[:1]))
                                             .annotate(time=Min('submission__date'))
                                             .values_list('problem_id', 'time', 'points'))

        for problem_id, time, points in queryset:
            if self.config['cumtime']:
                dt = (time - participation.start).total_seconds()
                if points:
                    cumtime += dt
            else:
                dt = 0

            format_data[str(problem_id)] = {'points': points, 'time': dt}
            score += points

        participation.cumtime = max(cumtime, 0)
        participation.score = score
        participation.tiebreaker = 0
        participation.format_data = format_data
        participation.save() 
Example #20
Source File: api_v2.py    From online-judge with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_unfiltered_queryset(self):
        latest_rating_subquery = Rating.objects.filter(user=OuterRef('pk')).order_by('-contest__end_time')
        return (
            Profile.objects
            .filter(is_unlisted=False, user__is_active=True)
            .annotate(
                username=F('user__username'),
                latest_rating=Subquery(latest_rating_subquery.values('rating')[:1]),
                latest_volatility=Subquery(latest_rating_subquery.values('volatility')[:1]),
            )
            .order_by('id')
            .only('id', 'points', 'performance_points', 'problem_count', 'display_rank')
        ) 
Example #21
Source File: api.py    From cadasta-platform with GNU Affero General Public License v3.0 5 votes vote down vote up
def get_queryset(self):
        proj = self.get_content_object()
        related_content_objs = ContentObject.objects.filter(
            resource=OuterRef('id'),
            content_type=ContentType.objects.get_for_model(proj),
            object_id=proj.id)
        return super().get_queryset().prefetch_related(
            'content_objects__content_type').annotate(
            attached=Exists(related_content_objs)) 
Example #22
Source File: admin.py    From clist with Apache License 2.0 5 votes vote down vote up
def queryset(self, request, queryset):
        if self.value() in ['yes', 'no']:
            logins = Login.objects.filter(team=OuterRef('pk'), stage=OuterRef('status'))
            queryset = queryset.annotate(has_login=Exists(logins))
            queryset = queryset.filter(has_login=self.value() == 'yes')
        return queryset 
Example #23
Source File: parse_statistic.py    From clist with Apache License 2.0 5 votes vote down vote up
def handle(self, *args, **options):
        self.stdout.write(str(options))
        args = AttrDict(options)

        if args.resources:
            if len(args.resources) == 1:
                contests = Contest.objects.filter(resource__module__resource__host__iregex=args.resources[0])
            else:
                resources = [Resource.objects.get(host__iregex=r) for r in args.resources]
                contests = Contest.objects.filter(resource__module__resource__host__in=resources)
        else:
            has_module = Module.objects.filter(resource_id=OuterRef('resource__pk'))
            contests = Contest.objects.annotate(has_module=Exists(has_module)).filter(has_module=True)

        if args.only_new:
            has_statistics = Statistics.objects.filter(contest_id=OuterRef('pk'))
            contests = contests.annotate(has_statistics=Exists(has_statistics)).filter(has_statistics=False)

        if args.year:
            contests = contests.filter(start_time__year=args.year)

        self.parse_statistic(
            contests=contests,
            previous_days=args.days,
            limit=args.limit,
            with_check=not args.no_check_timing,
            stop_on_error=args.stop_on_error,
            random_order=args.random_order,
            no_update_results=args.no_update_results,
            freshness_days=args.freshness_days,
            title_regex=args.event,
            users=args.users,
            with_stats=not args.no_stats,
            update_without_new_rating=args.update_without_new_rating,
        ) 
Example #24
Source File: update_auto_rating.py    From clist with Apache License 2.0 5 votes vote down vote up
def handle(self, *args, **options):

        qs = AutoRating.objects.filter(deadline__gt=timezone.now())
        qs = qs.select_related('party')
        qs = qs.prefetch_related('party__rating_set')
        for auto_rating in tqdm.tqdm(qs, desc='update auto rating'):
            party = auto_rating.party
            contests = Contest.objects.filter(**auto_rating.info['filter'])

            party_contests = party.rating_set.filter(contest_id=OuterRef('pk'))
            contests = contests.annotate(in_party=Exists(party_contests)).filter(in_party=False)

            for contest in contests:
                rating = Rating(party=party, contest=contest)
                rating.save() 
Example #25
Source File: 0064_populate_labelling.py    From casepro with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def populate_labelling_msg_fields(apps, schema_editor):
    Labelling = apps.get_model("msgs", "Labelling")
    Message = apps.get_model("msgs", "Message")

    max_id = 0
    num_updated = 0
    while True:
        id_batch = list(
            Labelling.objects.filter(id__gt=max_id, message_created_on=None)
            .values_list("id", flat=True)
            .order_by("id")[:BATCH_SIZE]
        )
        if not id_batch:
            break

        Labelling.objects.filter(id__in=id_batch).update(
            message_is_flagged=Subquery(Message.objects.filter(id=OuterRef("message_id")).values("is_flagged")[:1]),
            message_is_archived=Subquery(Message.objects.filter(id=OuterRef("message_id")).values("is_archived")[:1]),
            message_created_on=Subquery(Message.objects.filter(id=OuterRef("message_id")).values("created_on")[:1]),
        )

        max_id = id_batch[-1]
        num_updated += len(id_batch)

        print(f" > Updated {num_updated} instances of labelling") 
Example #26
Source File: v1.py    From lexpredict-contraxsuite with GNU Affero General Public License v3.0 4 votes vote down vote up
def get_queryset(self):
        qs = super().get_queryset()
        qs = qs.filter(value__isnull=False, document__delete_pending=False)

        # via project router
        project_id = self.kwargs.get('project_pk')
        if project_id:
            qs = qs.filter(document__project_id=project_id)

        field_annotation_subquery = FieldAnnotation.objects \
            .filter(field=OuterRef("field"), document=OuterRef("document")) \
            .order_by('field', 'document') \
            .values('field', 'document') \
            .annotate(ann=GroupConcat('location_text', '\n-----\n'))

        qs = qs.annotate(
            modified_by_username=F('modified_by__username'),
            project=F('document__project__name'),
            project_id=F('document__project_id'),
            document_name=F('document__name'),
            document_status=F('document__status__name'),
            field_name=Concat('field__document_type__title', Value(': '), 'field__title'))

        qs = qs.select_related('document', 'document__project', 'document__status',
                               'field', 'field__document_type', 'modified_by')

        if self.action == 'list':
            qs = qs.annotate(
                location_text=Subquery(field_annotation_subquery.values('ann')[:1],
                                       output_field=TextField()))

        qs = qs.only(
            'document_id', 'document__name', 'document__status__name',
            'document__project_id', 'document__project__name',
            'field_id', 'field__title', 'field__type',
            'field__document_type__title',
            'value',
            'modified_by_id', 'modified_by__username', 'modified_date')

        return qs


# --------------------------------------------------------
#  Field Annotation Status Views
# -------------------------------------------------------- 
Example #27
Source File: models.py    From janeway with GNU Affero General Public License v3.0 4 votes vote down vote up
def get_sorted_articles(self, published_only=True):
        """ Returns issue articles sorted by section and article order

        Many fields are prefetched and annotated to handle large issues more
        eficiently. In particular, it annotates relevant SectionOrder and
        ArticleOrdering rows as section_order and article_order respectively.
        Returns a Queryset which should keep the memory footprint at a minimum
        """

        section_order_subquery = SectionOrdering.objects.filter(
            section=OuterRef("section__pk"),
            issue=Value(self.pk),
        ).values_list("order")

        article_order_subquery = ArticleOrdering.objects.filter(
            section=OuterRef("section__pk"),
            article=OuterRef("pk"),
            issue=Value(self.pk),
        ).values_list("order")

        issue_articles = self.articles.prefetch_related(
            'authors',
            'frozenauthor_set',
            'manuscript_files',
        ).select_related(
            'section',
        ).annotate(
            section_order=Subquery(section_order_subquery),
            article_order=Subquery(article_order_subquery),
        ).order_by(
            "section_order",
            "section__sequence",
            "section__pk",
            "article_order",
        )

        if published_only:
            issue_articles = issue_articles.filter(
                stage=submission_models.STAGE_PUBLISHED,
                date_published__lte=timezone.now(),
            )

        return issue_articles 
Example #28
Source File: result_records.py    From open-context-py with GNU General Public License v3.0 4 votes vote down vote up
def _get_string_attribute_values(self, uuids, string_pred_uuids):
        """Gets string attribute values from the database

        :param list uuids: List of UUIDs for the solr documents in the
            results that may have string attributes.
        :param list string_pred_uuids: List of string predicates from
            solr docs
        """

        if not len(string_pred_uuids):
            # Return an empty dict if there are no string predicates.
            return {}

        # NOTE: We need to query the database to get the string content
        # associated with string attribute predicates, because we do
        # not store this in solr.
        
        # This queryset will be in a SubQuery to effectively make a 
        # join between Assertions and OC strings via the 
        # assertion.object_uuid and ocstring.uuid keys.
        str_qs = OCstring.objects.filter(
            uuid=OuterRef('object_uuid')
        ).values('content')

        ass_qs = Assertion.objects.filter(
            uuid__in=uuids,
            predicate_uuid__in=string_pred_uuids,
        ).exclude(
            visibility__lt=1
        ).order_by(
            'uuid', 
            'predicate_uuid', 
            'sort'
        ).annotate(
            str_content=Subquery(
                str_qs
            )
        )
        output = {}
        for a in ass_qs:
            if not a.uuid in output:
                output[a.uuid] = {}
            if not a.predicate_uuid in output[a.uuid]:
                output[a.uuid][a.predicate_uuid] = []
            output[a.uuid][a.predicate_uuid].append(
                a.str_content
            )
        return output 
Example #29
Source File: ecoo.py    From online-judge with GNU Affero General Public License v3.0 4 votes vote down vote up
def update_participation(self, participation):
        cumtime = 0
        score = 0
        format_data = {}

        submissions = participation.submissions.exclude(submission__result__in=('IE', 'CE'))

        submission_counts = {
            data['problem_id']: data['count'] for data in submissions.values('problem_id').annotate(count=Count('id'))
        }
        queryset = (
            submissions
            .values('problem_id')
            .filter(
                submission__date=Subquery(
                    submissions
                    .filter(problem_id=OuterRef('problem_id'))
                    .order_by('-submission__date')
                    .values('submission__date')[:1],
                ),
            )
            .annotate(points=Max('points'))
            .values_list('problem_id', 'problem__points', 'points', 'submission__date')
        )

        for problem_id, problem_points, points, date in queryset:
            sub_cnt = submission_counts.get(problem_id, 0)

            dt = (date - participation.start).total_seconds()

            bonus = 0
            if points > 0:
                # First AC bonus
                if sub_cnt == 1 and points == problem_points:
                    bonus += self.config['first_ac_bonus']
                # Time bonus
                if self.config['time_bonus']:
                    bonus += (participation.end_time - date).total_seconds() // 60 // self.config['time_bonus']

            format_data[str(problem_id)] = {'time': dt, 'points': points, 'bonus': bonus}

        for data in format_data.values():
            if self.config['cumtime']:
                cumtime += data['time']
            score += data['points'] + data['bonus']

        participation.cumtime = cumtime
        participation.score = score
        participation.tiebreaker = 0
        participation.format_data = format_data
        participation.save() 
Example #30
Source File: api_v1.py    From online-judge with GNU Affero General Public License v3.0 4 votes vote down vote up
def api_v1_contest_detail(request, contest):
    contest = get_object_or_404(Contest, key=contest)

    if not contest.is_accessible_by(request.user):
        raise Http404()

    in_contest = contest.is_in_contest(request.user)
    can_see_rankings = contest.can_see_full_scoreboard(request.user)

    problems = list(contest.contest_problems.select_related('problem')
                    .defer('problem__description').order_by('order'))

    new_ratings_subquery = Rating.objects.filter(participation=OuterRef('pk'))
    old_ratings_subquery = (Rating.objects.filter(user=OuterRef('user__pk'),
                                                  contest__end_time__lt=OuterRef('contest__end_time'))
                            .order_by('-contest__end_time'))
    participations = (contest.users.filter(virtual=0, user__is_unlisted=False)
                      .annotate(new_rating=Subquery(new_ratings_subquery.values('rating')[:1]))
                      .annotate(old_rating=Subquery(old_ratings_subquery.values('rating')[:1]))
                      .prefetch_related('user__organizations')
                      .annotate(username=F('user__user__username'))
                      .order_by('-score', 'cumtime', 'tiebreaker') if can_see_rankings else [])
    can_see_problems = (in_contest or contest.ended or contest.is_editable_by(request.user))

    return JsonResponse({
        'time_limit': contest.time_limit and contest.time_limit.total_seconds(),
        'start_time': contest.start_time.isoformat(),
        'end_time': contest.end_time.isoformat(),
        'tags': list(contest.tags.values_list('name', flat=True)),
        'is_rated': contest.is_rated,
        'rate_all': contest.is_rated and contest.rate_all,
        'has_rating': contest.ratings.exists(),
        'rating_floor': contest.rating_floor,
        'rating_ceiling': contest.rating_ceiling,
        'format': {
            'name': contest.format_name,
            'config': contest.format_config,
        },
        'problems': [
            {
                'points': int(problem.points),
                'partial': problem.partial,
                'name': problem.problem.name,
                'code': problem.problem.code,
            } for problem in problems] if can_see_problems else [],
        'rankings': [
            {
                'user': participation.username,
                'points': participation.score,
                'cumtime': participation.cumtime,
                'tiebreaker': participation.tiebreaker,
                'old_rating': participation.old_rating,
                'new_rating': participation.new_rating,
                'is_disqualified': participation.is_disqualified,
                'solutions': contest.format.get_problem_breakdown(participation, problems),
            } for participation in participations],
    })