Python django.db.models.Case() Examples

The following are 30 code examples for showing how to use django.db.models.Case(). 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: kobo-predict   Author: awemulya   File: ScheduleViewset.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def filter_queryset(self, queryset):
        if self.request.user.is_anonymous():
            self.permission_denied(self.request)
        is_project = self.kwargs.get('is_project', None)
        pk = self.kwargs.get('pk', None)
        if is_project == "1":
            queryset = queryset.filter(project__id=pk)
            return queryset.annotate(response_count=Count("schedule_forms__project_form_instances")).select_related('schedule_forms', 'schedule_forms__xf', 'schedule_forms__em')
        else:
            project_id = get_object_or_404(Site, pk=pk).project.id
            queryset = queryset.filter(Q(site__id=pk, schedule_forms__from_project=False)
                                       | Q(project__id=project_id))
            return queryset.annotate(
                site_response_count=Count("schedule_forms__site_form_instances", ),
                response_count=Count(Case(
                    When(project__isnull=False, schedule_forms__project_form_instances__site__id=pk, then=F('schedule_forms__project_form_instances')),
                    output_field=IntegerField(),
                ), distinct=True)

            ).select_related('schedule_forms','schedule_forms__xf', 'schedule_forms__em') 
Example 2
Project: kobo-predict   Author: awemulya   File: FieldSightXformViewset.py    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
def filter_queryset(self, queryset):
        if self.request.user.is_anonymous():
            self.permission_denied(self.request)
        is_project = self.kwargs.get('is_project', None)
        pk = self.kwargs.get('pk', None)
        if is_project == "1":
            queryset = queryset.filter(project__id=pk)
            return queryset.select_related('xf', 'em')
        else:
            project_id = get_object_or_404(Site, pk=pk).project.id
            queryset = queryset.filter(Q(site__id=pk, from_project=False)
                                       | Q (project__id=project_id))
            return queryset.annotate(
                site_response_count=Count("site_form_instances",),
                response_count=Count(Case(
                    When(project__isnull=False, project_form_instances__site__id=pk, then=F('project_form_instances')),
                    output_field=IntegerField(),
                ), distinct=True)

            ).select_related('xf', 'em') 
Example 3
Project: wagtailmenus   Author: rkhleics   File: menus.py    License: MIT License 6 votes vote down vote up
def get_for_site(cls, handle, site, fall_back_to_default_site_menus=False):
        """Return a FlatMenu instance with a matching ``handle`` for the
        provided ``site``, or for the default site (if suitable). If no
        match is found, returns None."""
        queryset = cls.objects.filter(handle__exact=handle)

        site_q = Q(site=site)
        if fall_back_to_default_site_menus:
            site_q |= Q(site__is_default_site=True)
        queryset = queryset.filter(site_q)

        # return the best match or None
        return queryset.annotate(matched_provided_site=Case(
            When(site_id=site.id, then=1), default=0,
            output_field=BooleanField()
        )).order_by('-matched_provided_site').first() 
Example 4
def populate_tracking_fields(apps, schema_editor):
    managers = [
        apps.get_model('hosting', 'Phone')._default_manager.all(),
        apps.get_model('hosting', 'Place')._default_manager.all(),
        apps.get_model('hosting', 'Profile')._default_manager.all(),
        apps.get_model('hosting', 'Website')._default_manager.all(),
    ]

    for objects in managers:
        objects.update(
            deleted_on=Case(
                When(deleted=False, then=None),
                default=F('modified'),
                output_field=DateTimeField())
        )
        objects.update(
            checked_on=Case(
                When(checked=False, then=None),
                default=F('modified'),
                output_field=DateTimeField())
        ) 
Example 5
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 6
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 7
Project: mangaki   Author: mangaki   File: work_merge.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def redirect_staff(self):
        target_work_staff = set()
        kept_staff_ids = []
        # Only one query: put self.target_work's Staff objects first in the list
        queryset = (Staff.objects.filter(work__in=self.works_to_merge)
            .annotate(belongs_to_target_work=Case(
                When(work_id=self.target_work.id, then=Value(1)),
                     default=Value(0), output_field=IntegerField()))
            .order_by('-belongs_to_target_work')
            .values_list('id', 'work_id', 'artist_id', 'role_id'))
        for staff_id, work_id, artist_id, role_id in queryset:
            if work_id == self.target_work.id:  # This condition will be met for the first iterations
                target_work_staff.add((artist_id, role_id))
            # Now we are sure we know every staff of the final work
            elif (artist_id, role_id) not in target_work_staff:
                kept_staff_ids.append(staff_id)
        Staff.objects.filter(work__in=self.works_to_merge).exclude(work_id=self.target_work.id).exclude(
            id__in=kept_staff_ids).delete()
        Staff.objects.filter(id__in=kept_staff_ids).update(work_id=self.target_work.id) 
Example 8
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 9
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 10
Project: lexpredict-contraxsuite   Author: LexPredict   File: models.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def get(cls, as_dataframe: bool = True, **filter_kwargs):
        """
        Return grouped by method/name statistic with AVG time and N calls
        :param as_dataframe: bool - whether return pandas.dataframe or plain QuerySet
        :param filter_kwargs: positional arguments represents options for filter() qs method
        :return: pandas Dataframe OR QuerySet
        """
        # .filter(has_error=False)\
        qs = cls.objects\
            .values('method', 'path', 'name')\
            .annotate(calls=Count('id'),
                      errors=Count(Case(
                          When(has_error=True, then=1),
                          output_field=IntegerField(),
                      )),
                      avg_time=Avg('time'), max_time=Max('time'))\
            .filter(**filter_kwargs)
        qs = list(qs)
        qs.sort(key=lambda m: -m['calls'])
        if as_dataframe:
            return pd.DataFrame.from_records(qs, columns=['name', 'method',
                                                          'calls', 'errors',
                                                          'avg_time', 'max_time'])
        return qs 
Example 11
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 12
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 13
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 14
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 15
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 16
Project: wagtail-review   Author: wagtail   File: models.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_pages_with_reviews_for_user(cls, user):
        """
        Return a queryset of pages which have reviews, for which the user has edit permission
        """
        user_perms = UserPagePermissionsProxy(user)
        reviewed_pages = (
            cls.objects
            .order_by('-submitted_at')
            .values_list('page_revision__page_id', 'submitted_at')
        )
        # Annotate datetime when a review was last created for this page
        last_review_requested_at = Case(
            *[
                When(pk=pk, then=Value(submitted_at))
                for pk, submitted_at in reviewed_pages
            ],
            output_field=models.DateTimeField(),
        )
        return (
            user_perms.editable_pages()
            .filter(pk__in=(page[0] for page in reviewed_pages))
            .annotate(last_review_requested_at=last_review_requested_at)
            .order_by('-last_review_requested_at')
        ) 
Example 17
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 18
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 19
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 20
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 21
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 22
Project: timed-backend   Author: adfinis-sygroup   File: serializers.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_verified(self, instance):
        queryset = instance["queryset"]
        queryset = queryset.annotate(
            verified=Case(
                When(verified_by_id__isnull=True, then=False),
                default=True,
                output_field=BooleanField(),
            )
        )
        instance["queryset"] = queryset
        return self._intersection(instance, "verified") 
Example 23
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 24
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 25
def convert_email_notification_setting(apps, schema_editor):
    ConversationParticipant = apps.get_model('conversations', 'ConversationParticipant')
    ConversationParticipant.objects.all().update(
        muted=Case(
            When(email_notifications=False, then=True),
            default=False,
        )
    ) 
Example 26
Project: karrot-backend   Author: yunity   File: api.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def statistics(self, request, pk=None):
        instance = self.get_object()
        weight = instance.activities.annotate(
            feedback_weight=Case(
                When(feedback_as_sum=True, then=Sum('feedback__weight')),
                default=Avg('feedback__weight'),
                output_field=FloatField()
            )
        ).aggregate(result_weight=Sum('feedback_weight'))['result_weight']
        data = {
            'feedback_count': instance.feedback_count,
            'feedback_weight': round(weight or 0),
            'activities_done': instance.activities_done,
        }
        return Response(data) 
Example 27
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 28
Project: pasportaservo   Author: tejoesperanto   File: models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def get_queryset(self):
        return PublishedQueryset(self.model, using=self._db).annotate(
            published=Case(
                When(pub_date__isnull=True, then=False),
                When(pub_date__gt=timezone.now(), then=False),
                default=True,
                output_field=BooleanField()
            ),
            has_more=Case(
                When(~Q(body=F('description')), then=True),
                default=False,
                output_field=BooleanField()
            ),
        ) 
Example 29
Project: zulip   Author: zulip   File: 0223_rename_to_is_muted.py    License: Apache License 2.0 5 votes vote down vote up
def set_initial_value_for_is_muted(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
    Subscription = apps.get_model("zerver", "Subscription")
    Subscription.objects.update(is_muted=Case(
        When(in_home_view=True, then=Value(False)),
        When(in_home_view=False, then=Value(True)),
    )) 
Example 30
Project: zulip   Author: zulip   File: 0223_rename_to_is_muted.py    License: Apache License 2.0 5 votes vote down vote up
def reverse_code(apps: StateApps, schema_editor: DatabaseSchemaEditor) -> None:
    Subscription = apps.get_model("zerver", "Subscription")
    Subscription.objects.update(in_home_view=Case(
        When(is_muted=True, then=Value(False)),
        When(is_muted=False, then=Value(True)),
    ))