Python django.db.models.When() Examples

The following are 30 code examples for showing how to use django.db.models.When(). 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: pasportaservo   Author: tejoesperanto   File: managers.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get_queryset(self):
        try:
            validity_period = SiteConfiguration.get_solo().confirmation_validity_period
        except DatabaseError:
            from datetime import timedelta
            validity_period = timedelta(weeks=42)
        validity_start = timezone.now() - validity_period
        return super().get_queryset().annotate(deleted=Case(
            When(deleted_on__isnull=True, then=False),
            default=True,
            output_field=BooleanField()
        )).annotate(confirmed=Case(
            When(confirmed_on__isnull=True, then=False),
            When(confirmed_on__lt=validity_start, then=False),
            default=True,
            output_field=BooleanField()
        )).annotate(checked=Case(
            When(checked_on__isnull=True, then=False),
            # When(checked_on__lt=validity_start, then=False),  # Temporarily disabled.
            default=True,
            output_field=BooleanField()
        )).select_related() 
Example 2
Project: mangaki   Author: mangaki   File: views.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def fix_index(request):
    suggestion_list = Suggestion.objects.select_related('work', 'user').prefetch_related(
        'work__category', 'evidence_set__user').annotate(
            count_agrees=Count(Case(When(evidence__agrees=True, then=1))),
            count_disagrees=Count(Case(When(evidence__agrees=False, then=1)))
        ).all().order_by('is_checked', '-date')

    paginator = Paginator(suggestion_list, FIXES_PER_PAGE)
    page = request.GET.get('page')

    try:
        suggestions = paginator.page(page)
    except PageNotAnInteger:
        suggestions = paginator.page(1)
    except EmptyPage:
        suggestions = paginator.page(paginator.num_pages)

    context = {
        'suggestions': suggestions
    }

    return render(request, 'fix/fix_index.html', context) 
Example 3
Project: byro   Author: byro   File: transaction.py    License: Apache License 2.0 6 votes vote down vote up
def with_balances(self):
        qs = self.annotate(
            balances_debit=models.Sum(
                models.Case(
                    models.When(
                        ~models.Q(bookings__debit_account=None), then="bookings__amount"
                    ),
                    default=0,
                    output_field=models.DecimalField(max_digits=8, decimal_places=2),
                )
            ),
            balances_credit=models.Sum(
                models.Case(
                    models.When(
                        ~models.Q(bookings__credit_account=None),
                        then="bookings__amount",
                    ),
                    default=0,
                    output_field=models.DecimalField(max_digits=8, decimal_places=2),
                )
            ),
        )
        return qs 
Example 4
Project: byro   Author: byro   File: transaction.py    License: Apache License 2.0 6 votes vote down vote up
def with_transaction_balances(self):
        qs = self.annotate(
            transaction_balances_debit=models.Sum(
                models.Case(
                    models.When(
                        ~models.Q(transaction__bookings__debit_account=None),
                        then="transaction__bookings__amount",
                    ),
                    default=0,
                    output_field=models.DecimalField(max_digits=8, decimal_places=2),
                )
            ),
            transaction_balances_credit=models.Sum(
                models.Case(
                    models.When(
                        ~models.Q(transaction__bookings__credit_account=None),
                        then="transaction__bookings__amount",
                    ),
                    default=0,
                    output_field=models.DecimalField(max_digits=8, decimal_places=2),
                )
            ),
        )
        return qs 
Example 5
Project: online-judge   Author: DMOJ   File: contests.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def make_contest_ranking_profile(contest, participation, contest_problems):
    def display_user_problem(contest_problem):
        # When the contest format is changed, `format_data` might be invalid.
        # This will cause `display_user_problem` to error, so we display '???' instead.
        try:
            return contest.format.display_user_problem(participation, contest_problem)
        except (KeyError, TypeError, ValueError):
            return mark_safe('<td>???</td>')

    user = participation.user
    return ContestRankingProfile(
        id=user.id,
        user=user.user,
        css_class=user.css_class,
        username=user.username,
        points=participation.score,
        cumtime=participation.cumtime,
        tiebreaker=participation.tiebreaker,
        organization=user.organization,
        participation_rating=participation.rating.rating if hasattr(participation, 'rating') else None,
        problem_cells=[display_user_problem(contest_problem) for contest_problem in contest_problems],
        result_cell=contest.format.display_participation_result(participation),
        participation=participation,
    ) 
Example 6
Project: zing   Author: evernote   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def validate_email(self):
        """Ensure emails are unique across the models tracking emails.

        Since it's essential to keep email addresses unique to support our
        workflows, a `ValidationError` will be raised if the email trying
        to be saved is already assigned to some other user.
        """
        lookup = Q(email__iexact=self.email)
        if self.pk is not None:
            # When there's an update, ensure no one else has this address
            lookup &= ~Q(user=self)

        try:
            EmailAddress.objects.get(lookup)
        except EmailAddress.DoesNotExist:
            pass
        else:
            raise ValidationError({"email": [_("This email address already exists.")]}) 
Example 7
Project: registrasion   Author: chrisjrn   File: conditions.py    License: Apache License 2.0 6 votes vote down vote up
def pre_filter(self, queryset, user):
        ''' Returns all of the items from queryset where the date falls into
        any specified range, but not yet where the stock limit is not yet
        reached.'''

        now = timezone.now()

        # Keep items with no start time, or start time not yet met.
        queryset = queryset.filter(Q(start_time=None) | Q(start_time__lte=now))
        queryset = queryset.filter(Q(end_time=None) | Q(end_time__gte=now))

        # Filter out items that have been reserved beyond the limits
        quantity_or_zero = self._calculate_quantities(user)

        remainder = Case(
            When(limit=None, then=Value(_BIG_QUANTITY)),
            default=F("limit") - Sum(quantity_or_zero),
        )

        queryset = queryset.annotate(remainder=remainder)
        queryset = queryset.filter(remainder__gt=0)

        return queryset 
Example 8
Project: eventoL   Author: eventoL   File: models.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_queryset(self):
        today = timezone.localdate()
        return super() \
            .get_queryset() \
            .annotate(attendees_count=models.Count('attendee', distinct=True)) \
            .annotate(last_date=models.Max('eventdate__date')) \
            .annotate(activity_proposal_is_open=models.Case(
                models.When(models.Q(limit_proposal_date__gte=today), then=True),
                default=False,
                output_field=models.BooleanField()
            )) \
            .annotate(registration_is_open=models.Case(
                models.When(models.Q(last_date__gte=today), then=True),
                default=False,
                output_field=models.BooleanField()
            )) 
Example 9
Project: instiapp-api   Author: wncc   File: misc.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def query_search(  # pylint: disable=too-many-arguments
        request, min_length, queryset, fields, collection, order_relevance=False):
    """Returns queryset with search filter."""
    search = request.GET.get('query')
    if search is not None and len(search) >= min_length:
        # Use a FTS backend if we have one
        if settings.USE_SONIC:
            ids = run_query_sync(collection, search)
            queryset = queryset.filter(id__in=ids)

            # Preserve order of returned results
            if order_relevance:
                preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(ids)])
                queryset = queryset.order_by(preserved)

            return queryset

        # Fallback if we are so quiet ;)
        return query_search_fallback(queryset, fields, search)  # pragma: no cover

    return queryset 
Example 10
Project: madewithwagtail   Author: springload   File: models.py    License: MIT License 6 votes vote down vote up
def children(self):
        user_ordering = self.SITES_ORDERING[self.sites_ordering]['ordering']
        pages = WagtailSitePage.objects.live().filter(Q(path__startswith=self.path) | Q(in_cooperation_with=self))

        # When ordering by `path`, the collaborations would either all be listed first or last
        # depending on whether the collaborator(s) page(s) was created before or after this page.
        # Adding an overwrite here so collaborations always appear last.
        if self.sites_ordering == self.SITES_ORDERING_PATH:
            pages = pages.annotate(
                is_own=Case(
                    When(path__startswith=self.path, then=Value(True)),
                    default_value=Value(False),
                    output_field=models.BooleanField(),
                )
            ).order_by('is_own', *user_ordering)

        # When ordering alphabetically or by creation date,
        # own sites and collaboration sites will be sorted together.
        else:
            pages = pages.order_by(*user_ordering)

        return pages 
Example 11
Project: orcamentos   Author: rg3915   File: views.py    License: MIT License 6 votes vote down vote up
def get_context_data(self, **kwargs):
        p = Proposal.objects.aggregate(
            proposals=Count('pk'),
            proposal_elab=Count(
                Case(When(status='elab', then=1), output_field=IntegerField())),
            proposal_pending=Count(
                Case(When(status='p', then=1), output_field=IntegerField())),
            proposal_concluded=Count(
                Case(When(status='co', then=1), output_field=IntegerField())),
            proposal_approved=Count(
                Case(When(status='a', then=1), output_field=IntegerField())),
            proposal_canceled=Count(
                Case(When(status='c', then=1), output_field=IntegerField())),
        )
        context = super(Dashboard, self).get_context_data(**kwargs)
        context['proposals'] = p
        context['proposal_list'] = self.proposal_list()
        context['proposal_elab'] = self.proposal_elab()
        context['entrys'] = self.entry_list()
        context['contract_total_per_month'] = self.contract_total_per_month()
        context['contract_total_per_year'] = self.contract_total_per_year()

        return context 
Example 12
Project: logtacts   Author: phildini   File: contact_list_views.py    License: MIT License 6 votes vote down vote up
def get_queryset(self):
        if not (hasattr(self, '_queryset') and self._queryset):
            base_queryset = super(ContactListView, self).get_queryset()
            if self.request.GET.get('q'):
                search_contacts = self.get_search_contacts()
                preserved = Case(*[When(pk=pk, then=pos) for pos, pk in enumerate(search_contacts)])
                base_queryset = base_queryset.filter(
                    id__in=search_contacts
                ).order_by(preserved)
            self._queryset = base_queryset.annotate(has_last_contact=Count('last_contact'))
            sort = self.request.GET.get('s')
            if sort == 'oldnew':
                self._queryset = self._queryset.order_by('-has_last_contact','last_contact')
            if sort == 'newold':
                self._queryset = self._queryset.order_by('-has_last_contact','-last_contact')
            if sort == 'za':
                self._queryset = self._queryset.order_by('-name')
            if sort == 'az':
                self._queryset = self._queryset.order_by('name')
            if not self.request.GET.get('q') and not sort:
                self._queryset = self._queryset.order_by('-has_last_contact','-last_contact')
            self._queryset = self._queryset.prefetch_related('tags')
        return self._queryset 
Example 13
Project: Django-3-Web-Development-Cookbook-Fourth-Edition   Author: PacktPublishing   File: views.py    License: MIT License 6 votes vote down vote up
def viral_video_detail(request, pk):
    yesterday = now() - timedelta(days=1)

    qs = ViralVideo.objects.annotate(
        total_views=models.F("authenticated_views") + models.F("anonymous_views"),
        label=models.Case(
            models.When(total_views__gt=POPULAR_FROM, then=models.Value("popular")),
            models.When(created__gt=yesterday, then=models.Value("new")),
            default=models.Value("cool"),
            output_field=models.CharField(),
        ),
    )

    # DEBUG: check the SQL query that Django ORM generates
    logger.debug(f"Query: {qs.query}")

    qs = qs.filter(pk=pk)
    if request.user.is_authenticated:
        qs.update(authenticated_views=models.F("authenticated_views") + 1)
    else:
        qs.update(anonymous_views=models.F("anonymous_views") + 1)

    video = get_object_or_404(qs)

    return render(request, "viral_videos/viral_video_detail.html", {"video": video}) 
Example 14
def get_aggregate_engagement_data(self, course_id):
        seven_days_ago = now() - datetime.timedelta(days=7)
        dict_list = [
            ('videos_overall', When(entity_type='video', then='count')),
            ('videos_last_week', When(entity_type='video', created__gt=seven_days_ago, then=1)),
            ('problems_overall', When(entity_type='problem', then='count')),
            ('problems_last_week', When(entity_type='problem', created__gt=seven_days_ago, then='count')),
            ('correct_problems_overall', When(entity_type='problem', event='completed', then='count')),
            ('correct_problems_last_week', When(entity_type='problem', event='completed',
                                                created__gt=seven_days_ago, then='count')),
            ('problems_attempts_overall', When(entity_type='problem', event='attempted', then='count')),
            ('problems_attempts_last_week', When(entity_type='problem', event='attempted',
                                                 created__gt=seven_days_ago, then='count')),
            ('forum_posts_overall', When(entity_type='discussion', then='count')),
            ('forum_posts_last_week', When(entity_type='discussion', created__gt=seven_days_ago, then='count')),
        ]
        dict_parameters = {key: Sum(Case(val, output_field=IntegerField())) for key, val in dict_list}
        dict_parameters['date_last_active'] = Max('created')
        query = ModuleEngagement.objects.filter(course_id=course_id)\
            .values('username')\
            .annotate(**dict_parameters)
        return query 
Example 15
Project: steemprojects.com   Author: wise-team   File: views.py    License: MIT License 6 votes vote down vote up
def package_list(request, template_name="package/package_grid.html"):
    context = {
        'categories': [
            {
                "title_plural": category.title_plural,
                "count": category.project_count,
                "description": category.description,
                "packages": category.project_set.published().order_by("-repo_watchers", "name")
            }
            for category in Category.objects.annotate(
                project_count=Count(Case(When(project__is_published=True, then=1)))
            )
        ]
    }

    return render(request, template_name, context) 
Example 16
Project: resolwe   Author: genialis   File: viewsets.py    License: Apache License 2.0 5 votes vote down vote up
def list_with_post(self, request):
        """Endpoint handler."""
        if self.is_search_request():
            search = self.search()

            page = self.paginate_queryset(search)
            if page is None:
                items = search
            else:
                items = page

            try:
                primary_keys = []
                order_map_cases = []
                for order, item in enumerate(items):
                    pk = item[self.primary_key_field]
                    primary_keys.append(pk)
                    order_map_cases.append(When(pk=pk, then=Value(order)))

                queryset = (
                    self.get_queryset()
                    .filter(pk__in=primary_keys)
                    .order_by(Case(*order_map_cases, output_field=IntegerField()).asc())
                )
            except KeyError:
                raise KeyError(
                    "Combined viewset requires that your index contains a field with "
                    "the primary key. By default this field is called 'id', but you "
                    "can change it by setting primary_key_field."
                )

            # Pagination must be handled differently.
            serializer = self.get_serializer(queryset, many=True)
            if page is not None:
                return self.get_paginated_response(serializer.data)

            return Response(serializer.data)
        else:
            queryset = self.filter_queryset(self.get_queryset())
            return self.paginate_response(queryset) 
Example 17
Project: resolwe   Author: genialis   File: models.py    License: Apache License 2.0 5 votes vote down vote up
def default_storage_location(self) -> Optional["StorageLocation"]:
        """Return default storage location for this instance.

        This is a storage location using connector with the lowest priority.
        When multiple storage locations have same priority one of them is
        returned.

        Usually only StorageLocation objects with status OK are considered.
        When no such objects exist one of remaining objects is returned (this
        should only happen when data object is still processing). When no
        StorageLocation objects exist None is returned.

        When StorageLocation has ceonnector that is not defined in settings the
        default priority of 100 is applied to it.

        :returns: instance of StorageLocation class or None.
        :rtype: Optional[StorageLocation]
        """
        whens = [
            models.When(
                connector_name=connector_name, then=connectors[connector_name].priority,
            )
            for connector_name in connectors
        ]
        q_set_all = self.storage_locations.annotate(
            priority=models.Case(
                *whens,
                default=DEFAULT_CONNECTOR_PRIORITY,
                output_field=models.IntegerField(),
            )
        ).order_by("priority")
        q_set_done = q_set_all.filter(status=StorageLocation.STATUS_DONE)
        return q_set_done.first() or q_set_all.first() 
Example 18
Project: resolwe   Author: genialis   File: models.py    License: Apache License 2.0 5 votes vote down vote up
def file_storage(self) -> Optional[FileStorage]:
        """Get the file storage object that holds this object.

        When no such FileStorage exists None is returned.
        """
        storage_location = self.storage_locations.first()
        if storage_location is None:
            return None

        return storage_location.file_storage 
Example 19
Project: kobo-predict   Author: awemulya   File: bar_data_project.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def __init__(self, project):
        self.data = OrderedDict()
        
        
        data = Site.objects.filter(project_id = project.id).aggregate(
             unstarted = Sum(
                 Case(When(current_progress = 0, then= 1),
                      output_field = IntegerField())
             ),
             first = Sum(
                 Case(When(current_progress__gte = 1, current_progress__lt = 20, then= 1),
                      output_field = IntegerField())
             ),
             second = Sum(
                 Case(When(current_progress__gte = 20, current_progress__lt= 40, then= 1),
                      output_field = IntegerField())
             ),
             third = Sum(
                 Case(When(current_progress__gte = 40, current_progress__lt= 60, then= 1),
                      output_field = IntegerField())
             ),
             fourth = Sum(
                 Case(When(current_progress__gte = 60, current_progress__lt= 80, then= 1),
                      output_field = IntegerField())
             ),
             fifth = Sum(
                 Case(When(current_progress__gte = 80, current_progress__lt= 100, then= 1),
                      output_field = IntegerField())
             ),
            sixth = Sum(
                 Case(When(current_progress = 100, then = 1),
                      output_field = IntegerField())
             )
        )
        self.data['Unstarted'] = 0 if data['unstarted'] is None else data['unstarted']
        self.data['< 20'] = 0 if data['first'] is None else data['first']
        self.data['20 - 40'] = 0 if data['second'] is None else data['second']
        self.data['40 - 60'] = 0 if data['third'] is None else data['third']
        self.data['60 - 80'] = 0 if data['fourth'] is None else data['fourth']
        self.data['80 <'] = 0 if data['fifth'] is None else data['fifth']
        self.data['Completed'] = 0 if data['sixth'] is None else data['sixth'] 
Example 20
Project: kobo-predict   Author: awemulya   File: models.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def get_submissions_count(self):
        qs = self.project_instances.aggregate(
            outstanding=Count(Case(When(form_status=0, project=self, then=1), output_field=IntegerField(),)),
            flagged=Count(Case(When(form_status=2, project=self, then=1), output_field=IntegerField(),)),
            approved=Count(Case(When(form_status=3, project=self, then=1), output_field=IntegerField(),)),
            rejected=Count(Case(When(form_status=1, project=self, then=1), output_field=IntegerField(),)),
        )
        return qs.get('outstanding', 0), qs.get('flagged', 0), qs.get('approved', 0), qs.get('rejected', 0) 
Example 21
Project: django-more   Author: ashleywaite   File: orderbyfield.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def set_group_order(self, model_instance, id_list, *, field=None, reset_values=False, using=None):
        """ Set the ordering for a group
            * model_instance :: (bound) Source instance of the call
            * id_list :: List of primary keys (or a queryset) that will be moved
              to the end of their ordering set in order
              Has the effect of reordering all listed to match order specified
            * field :: Local fk that connects to source model if it's remote
            * reset_values :: Boolean to indicate whether to freshly renumber
              entire group from 0
              Must be updating entire group to reset_values
        """
        # Case expression to number instances in correct order
        enum_case = Case(*[When(pk=pk, then=i) for i, pk in enumerate(id_list)])
        # Bulk update with next value + enumerated value
        group_qs = self.get_group(model_instance)
        update_qs = group_qs.filter(pk__in=id_list)
        update_count = update_qs.update(**{self.attname: self.get_next_expression(model_instance) + enum_case})
        # Can only safely reset up whole group was updated
        if reset_values and update_count == group_qs.count():
            # Bulk update with just enumerated value
            update_qs.update(**{self.attname: enum_case})

        # TODO Even better with enumerated CTE

        # NOTE Possible fallback for some dbs? Update sequentially
        # for pk in id_list:
        #    qs.filter(pk=pk).update(**{self.attname: value}) 
Example 22
Project: hutils   Author: zaihui   File: databases.py    License: MIT License 5 votes vote down vote up
def annotate_sum(self, key: str, **queries):
        """ 实现 Sum/Case/When 的一套快捷方式

        Examples::

            queryset.annotate_sum('is_followed', followers__followee=account)

        Equals to::

            queryset.annotate(is_followed=Sum(Case(When(followers__followee=account, then=1), default=0)))
        """
        queryset = self._queryset
        queries.setdefault("then", 1)
        return queryset.annotate(**{key: Sum(Case(When(**queries), default=0, output_field=IntegerField()))}) 
Example 23
Project: pasportaservo   Author: tejoesperanto   File: managers.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_queryset(self):
        return super().get_queryset().annotate(is_active=Case(
            When(active_from__gt=timezone.now(), then=False),
            When(active_until__lt=timezone.now(), then=False),
            default=True,
            output_field=BooleanField()
        )) 
Example 24
Project: rdmo   Author: rdmorganiser   File: views.py    License: Apache License 2.0 5 votes vote down vote up
def get_queryset(self):
        # prepare When statements for conditional expression
        case_args = []
        for role, text in Membership.ROLE_CHOICES:
            case_args.append(models.When(membership__role=role, then=models.Value(str(text))))

        return Project.objects.filter(user=self.request.user).annotate(role=models.Case(
            *case_args,
            default=None,
            output_field=models.CharField()
        )) 
Example 25
Project: online-judge   Author: DMOJ   File: contests.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_context_data(self, **kwargs):
        context = super(ContestDetail, self).get_context_data(**kwargs)
        context['contest_problems'] = Problem.objects.filter(contests__contest=self.object) \
            .order_by('contests__order').defer('description') \
            .annotate(has_public_editorial=Sum(Case(When(solution__is_public=True, then=1),
                                                    default=0, output_field=IntegerField()))) \
            .add_i18n_name(self.request.LANGUAGE_CODE)
        context['contest_has_public_editorials'] = any(
            problem.is_public and problem.has_public_editorial for problem in context['contest_problems']
        )
        return context 
Example 26
Project: lexpredict-contraxsuite   Author: LexPredict   File: v1.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_true_annotations_queryset(self):
        """
        Get FieldAnnotation queryset
        """
        true_ann_qs = self.get_initial_queryset(FieldAnnotation)

        # WARN: fields order makes sense here for list view
        true_ann_only_fields = [
            'status_id',
            'modified_by_id',
            'modified_date']

        # TODO: move common annotations into get_initial_queryset()
        # WARN: fields order makes sense here for list view
        true_ann_qs_annotate = OrderedDict(
            document_id=Cast('document_id', output_field=CharField()),
            project_id=F('document__project_id'),
            project_name=F('document__project__name'),
            document_name=F('document__name'),
            document_status=F('document__status__name'),
            field_name=F('field__title'),
            status_name=F('status__name'),
            assignee_name=Case(When(Q(assignee__name__isnull=False) & ~Q(assignee__name=''), then=F('assignee__name')),
                               When(Q(assignee__first_name__isnull=False) & ~Q(assignee__first_name='') &
                                    Q(assignee__last_name__isnull=False) & ~Q(assignee__last_name=''),
                                    then=Concat(F('assignee__first_name'), Value(' '), F('assignee__last_name'))),
                               default=F('assignee__username'),
                               output_field=CharField()
                               )
        )
        # WARN: MUST HAVE the same
        # 1. fields number
        # 2. fields order
        # for FieldAnnotation and FieldAnnotationFalseMatch querysets to perform UNION !!!
        # so .values() and .annotate() applies THE SAME fields number and order
        true_ann_fields = self.common_fields + true_ann_only_fields
        true_ann_qs = true_ann_qs.values(*true_ann_fields).annotate(**true_ann_qs_annotate)

        return true_ann_qs 
Example 27
Project: lexpredict-contraxsuite   Author: LexPredict   File: v1.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_false_annotations_queryset(self):
        """
        Get FieldAnnotationFalseMatch queryset
        """
        false_ann_qs = self.get_initial_queryset(FieldAnnotationFalseMatch)

        # TODO: move common annotations into get_initial_queryset()
        # WARN: fields order makes sense here for list view
        false_ann_qs = false_ann_qs.values(*self.common_fields).annotate(
            status_id=Value(FieldAnnotationStatus.rejected_status_pk(), output_field=IntegerField()),
            modified_by_id=Value(None, output_field=CharField()),
            modified_date=Value(None, output_field=DateField()),

            document_id=Cast('document_id', output_field=CharField()),
            project_id=F('document__project_id'),
            project_name=F('document__project__name'),
            document_name=F('document__name'),
            document_status=F('document__status__name'),
            field_name=F('field__title'),
            status_name=Value('Rejected', output_field=CharField()),
            assignee_name=Case(When(Q(assignee__name__isnull=False) & ~Q(assignee__name=''), then=F('assignee__name')),
                               When(assignee__first_name__isnull=False,
                                    assignee__last_name__isnull=False,
                                    then=Concat(F('assignee__first_name'), Value(' '), F('assignee__last_name'))),
                               default=F('assignee__username'),
                               output_field=CharField()
                               )
        )
        return false_ann_qs 
Example 28
Project: website   Author: outreachy   File: 0157_set_new_contributors_welcome.py    License: GNU General Public License v3.0 5 votes vote down vote up
def update_projects(apps, schema_editor):
    Project = apps.get_model('home.Project')
    Project.objects.all().update(
        new_contributors_welcome=models.Case(
            models.When(deadline="NOW", then=models.Value(False)),
            default=models.Value(True),
        ),
    ) 
Example 29
Project: wagtail   Author: wagtail   File: models.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def order_for_display(queryset):
        return queryset.annotate(
            display_order=Case(
                When(depth=1, then=Value('')),
                default='name')
        ).order_by('display_order') 
Example 30
Project: django-pivot   Author: martsberger   File: histogram.py    License: MIT License 5 votes vote down vote up
def between_include_start(column, start, end, value=1):
    return When(Q(**{column + '__gte': start, column + '__lt': end}), then=value)