Python django.db.models.Value() Examples

The following are 30 code examples for showing how to use django.db.models.Value(). 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: timed-backend   Author: adfinis-sygroup   File: views.py    License: GNU Affero General Public License v3.0 7 votes vote down vote up
def get_queryset(self):
        date = self._extract_date()
        user = self.request.user
        queryset = get_user_model().objects.values("id")
        queryset = queryset.annotate(date=Value(date, DateField()))
        # last_reported_date filter is set, a date can only be calucated
        # for users with either at least one absence or report
        if date is None:
            users_with_reports = Report.objects.values("user").distinct()
            users_with_absences = Absence.objects.values("user").distinct()
            active_users = users_with_reports.union(users_with_absences)
            queryset = queryset.filter(id__in=active_users)

        queryset = queryset.annotate(
            pk=Concat("id", Value("_"), "date", output_field=CharField())
        )

        if not user.is_superuser:
            queryset = queryset.filter(Q(id=user.id) | Q(supervisors=user))

        return queryset 
Example 2
Project: timed-backend   Author: adfinis-sygroup   File: views.py    License: GNU Affero General Public License v3.0 7 votes vote down vote up
def get_queryset(self):
        date = self._extract_date()
        user = self._extract_user()

        queryset = models.AbsenceType.objects.values("id")
        queryset = queryset.annotate(date=Value(date, DateField()))
        queryset = queryset.annotate(user=Value(user.id, IntegerField()))
        queryset = queryset.annotate(
            pk=Concat(
                "user", Value("_"), "id", Value("_"), "date", output_field=CharField()
            )
        )

        # only myself, superuser and supervisors may see by absence balances
        current_user = self.request.user

        if not current_user.is_superuser:
            if current_user.id != user.id:
                if not current_user.supervisees.filter(id=user.id).exists():
                    return models.AbsenceType.objects.none()

        return queryset 
Example 3
Project: timed-backend   Author: adfinis-sygroup   File: models.py    License: GNU Affero General Public License v3.0 6 votes vote down vote up
def for_user(self, user, start, end):
        """Get employments in given time frame for current user.

        This includes overlapping employments.

        :param User user: The user of the searched employments
        :param datetime.date start: start of time frame
        :param datetime.date end: end of time frame
        :returns: queryset of employments
        """
        # end date NULL on database is like employment is ending today
        queryset = self.annotate(
            end=functions.Coalesce("end_date", models.Value(date.today()))
        )
        return queryset.filter(user=user).exclude(
            models.Q(end__lt=start) | models.Q(start_date__gt=end)
        ) 
Example 4
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 5
Project: SMART   Author: RTIInternational   File: utils_queue.py    License: MIT License 6 votes vote down vote up
def get_queue_size_params(queue, queue_size, num_in_queue, batch_size, irr_queue):
    '''
    Get the sql parameters for the number of items to add to the queue
    '''
    # if there is less space in the queue than the default number of
    # elements to add, or we are trying to fill the queue to the top
    # (irr_queue=None in the second case)
    if (queue_size - num_in_queue < batch_size) or not(irr_queue):
        sample_size_sql, sample_size_params = (Queue.objects.filter(pk=queue.pk)
                                               .annotate(sample_size=F('length') - Count('data'))
                                               .values('sample_size')
                                               .query.sql_with_params())
    else:
        # just add the number requested (some percent of the batch size)
        sample_size_sql, sample_size_params = (Queue.objects.filter(pk=queue.pk)
                                               .annotate(sample_size=Value(batch_size, IntegerField()))
                                               .values('sample_size')
                                               .query.sql_with_params())
    return sample_size_sql, sample_size_params 
Example 6
Project: wagtail   Author: wagtail   File: backend.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def as_vector(self, texts, for_autocomplete=False):
        """
        Converts an array of strings into a SearchVector that can be indexed.
        """
        texts = [(text.strip(), weight) for text, weight in texts]
        texts = [(text, weight) for text, weight in texts if text]

        if not texts:
            return EMPTY_VECTOR

        search_config = self.autocomplete_config if for_autocomplete else self.config

        return ADD([
            SearchVector(Value(text, output_field=TextField()), weight=weight, config=search_config)
            for text, weight in texts
        ]) 
Example 7
Project: python   Author: Yeah-Kun   File: base.py    License: Apache License 2.0 6 votes vote down vote up
def __init__(self, expression, pos, length=None, **extra):
        """
        expression: the name of a field, or an expression returning a string
        pos: an integer > 0, or an expression returning an integer
        length: an optional number of characters to return
        """
        if not hasattr(pos, 'resolve_expression'):
            if pos < 1:
                raise ValueError("'pos' must be greater than 0")
            pos = Value(pos)
        expressions = [expression, pos]
        if length is not None:
            if not hasattr(length, 'resolve_expression'):
                length = Value(length)
            expressions.append(length)
        super(Substr, self).__init__(*expressions, **extra) 
Example 8
Project: registrasion   Author: chrisjrn   File: views.py    License: Apache License 2.0 6 votes vote down vote up
def credit_notes(request, form):
    ''' Shows all of the credit notes in the system. '''

    notes = commerce.CreditNote.objects.all().select_related(
        "creditnoterefund",
        "creditnoteapplication",
        "invoice",
        "invoice__user__attendee__attendeeprofilebase",
    )

    return QuerysetReport(
        "Credit Notes",
        ["id",
         "invoice__user__attendee__attendeeprofilebase__invoice_recipient",
         "status", "value"],
        notes,
        headings=["id", "Owner", "Status", "Value"],
        link_view=views.credit_note,
    ) 
Example 9
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 10
Project: django-mysql   Author: adamchainz   File: functions.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, *expressions, **kwargs):
        separator = kwargs.pop("separator", ",")
        if len(kwargs) > 0:
            raise ValueError(
                "Invalid keyword arguments for ConcatWS: {}".format(
                    ",".join(kwargs.keys())
                )
            )

        if len(expressions) < 2:
            raise ValueError("ConcatWS must take at least two expressions")

        if not hasattr(separator, "resolve_expression"):
            separator = Value(separator)

        # N.B. if separator is "," we could potentially use list field
        output_field = TextField()
        super().__init__(separator, *expressions, output_field=output_field) 
Example 11
Project: django-mysql   Author: adamchainz   File: functions.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, expression, *paths, output_field=None):
        from django_mysql.models.fields import JSONField

        exprs = [expression]
        for path in paths:
            if not hasattr(path, "resolve_expression"):
                path = Value(path)
            exprs.append(path)

        if output_field is not None:
            if len(paths) > 1:
                raise TypeError(
                    "output_field won't work with more than one path, as a "
                    "JSON Array will be returned"
                )
        else:
            output_field = JSONField()

        super().__init__(*exprs, output_field=output_field) 
Example 12
Project: django-mysql   Author: adamchainz   File: functions.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, expression, data):
        from django_mysql.models.fields import JSONField

        if not data:
            raise ValueError('"data" cannot be empty')

        exprs = [expression]

        for path, value in data.items():
            if not hasattr(path, "resolve_expression"):
                path = Value(path)

            exprs.append(path)

            if not hasattr(value, "resolve_expression"):
                value = JSONValue(value)

            exprs.append(value)

        super().__init__(*exprs, output_field=JSONField()) 
Example 13
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 14
Project: koku   Author: project-koku   File: query_handler.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def annotations(self):
        """Create dictionary for query annotations.

        Returns:
            (Dict): query annotations dictionary

        """
        units_fallback = self._mapper.report_type_map.get("cost_units_fallback")
        annotations = {
            "date": self.date_trunc("usage_start"),
            "cost_units": Coalesce(self._mapper.cost_units_key, Value(units_fallback)),
        }
        if self._mapper.usage_units_key:
            units_fallback = self._mapper.report_type_map.get("usage_units_fallback")
            annotations["usage_units"] = Coalesce(self._mapper.usage_units_key, Value(units_fallback))
        # { query_param: database_field_name }
        fields = self._mapper.provider_map.get("annotations")
        prefix_removed_parameters_list = list(
            map(
                lambda x: x if ":" not in x else x.split(":", maxsplit=1)[1],
                self.parameters.get("group_by", {}).keys(),
            )
        )
        for q_param, db_field in fields.items():
            if q_param in prefix_removed_parameters_list:
                annotations[q_param] = F(db_field)
        return annotations 
Example 15
Project: koku   Author: project-koku   File: query_handler.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _build_sum(self, query, annotations):
        """Build the sum results for the query."""
        sum_units = {}

        query_sum = self.initialize_totals()
        if not self.parameters.parameters.get("compute_count"):
            query_sum.pop("count", None)

        cost_units_fallback = self._mapper.report_type_map.get("cost_units_fallback")
        usage_units_fallback = self._mapper.report_type_map.get("usage_units_fallback")
        count_units_fallback = self._mapper.report_type_map.get("count_units_fallback")
        if query.exists():
            sum_annotations = {"cost_units": Coalesce(self._mapper.cost_units_key, Value(cost_units_fallback))}
            if self._mapper.usage_units_key:
                units_fallback = self._mapper.report_type_map.get("usage_units_fallback")
                sum_annotations["usage_units"] = Coalesce(self._mapper.usage_units_key, Value(units_fallback))
            sum_query = query.annotate(**sum_annotations)
            units_value = sum_query.values("cost_units").first().get("cost_units", cost_units_fallback)
            sum_units = {"cost_units": units_value}
            if self._mapper.usage_units_key:
                units_value = sum_query.values("usage_units").first().get("usage_units", usage_units_fallback)
                sum_units["usage_units"] = units_value
            if annotations.get("count_units"):
                sum_units["count_units"] = count_units_fallback
            query_sum = self.calculate_total(**sum_units)
        else:
            sum_units["cost_units"] = cost_units_fallback
            if annotations.get("count_units"):
                sum_units["count_units"] = count_units_fallback
            if annotations.get("usage_units"):
                sum_units["usage_units"] = usage_units_fallback
            query_sum.update(sum_units)
            self._pack_data_object(query_sum, **self._mapper.PACK_DEFINITIONS)
        return query_sum 
Example 16
Project: koku   Author: project-koku   File: query_handler.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def annotations(self):
        """Create dictionary for query annotations.

        Returns:
            (Dict): query annotations dictionary

        """
        units_fallback = self._mapper.report_type_map.get("cost_units_fallback")
        annotations = {
            "date": self.date_trunc("usage_start"),
            "cost_units": Coalesce(self._mapper.cost_units_key, Value(units_fallback)),
        }
        if self._mapper.usage_units_key:
            units_fallback = self._mapper.report_type_map.get("usage_units_fallback")
            annotations["usage_units"] = Coalesce(self._mapper.usage_units_key, Value(units_fallback))

        # { query_param: database_field_name }
        fields = self._mapper.provider_map.get("annotations")
        for q_param, db_field in fields.items():
            annotations[q_param] = Concat(db_field, Value(""))
        return annotations 
Example 17
Project: koku   Author: project-koku   File: query_handler.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _build_sum(self, query):
        """Build the sum results for the query."""
        sum_units = {}
        query_sum = self.initialize_totals()
        cost_units_fallback = self._mapper.report_type_map.get("cost_units_fallback")
        # usage_units_fallback = self._mapper.report_type_map.get('usage_units_fallback')
        count_units_fallback = self._mapper.report_type_map.get("count_units_fallback")
        if query.exists():
            sum_annotations = {"cost_units": Coalesce(self._mapper.cost_units_key, Value(cost_units_fallback))}
            # if self._mapper.usage_units_key:
            #     units_fallback = self._mapper.report_type_map.get('usage_units_fallback')
            #     sum_annotations['usage_units'] = Coalesce(self._mapper.usage_units_key,
            #                                               Value(units_fallback))
            sum_query = query.annotate(**sum_annotations)

            units_value = sum_query.values("cost_units").first().get("cost_units", cost_units_fallback)
            sum_units = {"cost_units": units_value}
            # if self._mapper.usage_units_key:
            #     units_value = sum_query.values('usage_units').first().get('usage_units',
            #                                                               usage_units_fallback)
            #     sum_units['usage_units'] = units_value
            if self._mapper.report_type_map.get("annotations", {}).get("count_units"):
                sum_units["count_units"] = count_units_fallback

            query_sum = self.calculate_total(**sum_units)
        else:
            sum_units["cost_units"] = cost_units_fallback
            if self._mapper.report_type_map.get("annotations", {}).get("count_units"):
                sum_units["count_units"] = count_units_fallback
            # if self._mapper.report_type_map.get('annotations', {}).get('usage_units'):
            #     sum_units['usage_units'] = usage_units_fallback
            query_sum.update(sum_units)
            self._pack_data_object(query_sum, **self._mapper.PACK_DEFINITIONS)
        return query_sum 
Example 18
Project: koku   Author: project-koku   File: helpers.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _populate_daily_summary_table(self):
        included_fields = ["usage_start", "usage_end", "usage_account_id", "availability_zone", "tags"]
        annotations = {
            "product_family": Concat("cost_entry_product__product_family", Value("")),
            "product_code": Concat("cost_entry_product__service_code", Value("")),
            "region": Concat("cost_entry_product__region", Value("")),
            "instance_type": Concat("cost_entry_product__instance_type", Value("")),
            "unit": Concat("cost_entry_pricing__unit", Value("")),
            "usage_amount": Sum("usage_amount"),
            "normalization_factor": Max("normalization_factor"),
            "normalized_usage_amount": Sum("normalized_usage_amount"),
            "currency_code": Max("currency_code"),
            "unblended_rate": Max("unblended_rate"),
            "unblended_cost": Sum("unblended_cost"),
            "blended_rate": Max("blended_rate"),
            "blended_cost": Sum("blended_cost"),
            "public_on_demand_cost": Sum("public_on_demand_cost"),
            "public_on_demand_rate": Max("public_on_demand_rate"),
            "resource_count": Count("resource_id", distinct=True),
            "resource_ids": ArrayAgg("resource_id", distinct=True),
        }

        entries = AWSCostEntryLineItemDaily.objects.values(*included_fields).annotate(**annotations)
        for entry in entries:
            alias = AWSAccountAlias.objects.filter(account_id=entry["usage_account_id"])
            alias = list(alias).pop() if alias else None
            summary = AWSCostEntryLineItemDailySummary(**entry, account_alias=alias)
            summary.save()
            self.current_month_total += entry["unblended_cost"] + entry["unblended_cost"] * Decimal(0.1)
        AWSCostEntryLineItemDailySummary.objects.update(markup_cost=F("unblended_cost") * 0.1) 
Example 19
Project: koku   Author: project-koku   File: tests_queries.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def test_filter_org_unit(self):
        """Check that the total is correct when filtering by org_unit_id."""
        with tenant_context(self.tenant):
            org_unit = "R_001"
            org_group_by_url = f"?filter[org_unit_id]={org_unit}"
            query_params = self.mocked_query_params(org_group_by_url, AWSCostView)
            handler = AWSReportQueryHandler(query_params)
            org_data = handler.execute_query()
            # grab the expected totals
            ten_days_ago = self.dh.n_days_ago(self.dh.today, 10)
            expected = AWSCostEntryLineItemDailySummary.objects.filter(
                usage_start__gte=ten_days_ago,
                usage_end__lte=self.dh.today,
                organizational_unit__org_unit_id__icontains=org_unit,
            ).aggregate(
                **{
                    "cost_total": Sum(
                        Coalesce(F("unblended_cost"), Value(0, output_field=DecimalField()))
                        + Coalesce(F("markup_cost"), Value(0, output_field=DecimalField()))
                    )
                }
            )
            # grab the actual totals for the org_unit_id filter
            org_cost_total = org_data.get("total").get("cost").get("total").get("value")
            org_infra_total = org_data.get("total").get("infrastructure").get("total").get("value")
            # make sure they add up
            expected_cost_total = expected.get("cost_total") or 0
            # infra and total cost match
            self.assertEqual(org_cost_total, expected_cost_total)
            self.assertEqual(org_infra_total, expected_cost_total) 
Example 20
Project: koku   Author: project-koku   File: helpers.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _populate_storage_daily_table(self):
        """Populate the daily table."""
        included_fields = [
            "namespace",
            "pod",
            "report_period_id",
            "persistentvolumeclaim",
            "persistentvolume",
            "storageclass",
            "persistentvolume_labels",
            "persistentvolumeclaim_labels",
        ]
        annotations = {
            "node": Value(random.choice(self.line_items).get("node"), output_field=CharField()),
            "usage_start": F("report__interval_start"),
            "usage_end": F("report__interval_start"),
            "persistentvolumeclaim_capacity_bytes": Max("persistentvolumeclaim_capacity_bytes"),
            "persistentvolumeclaim_capacity_byte_seconds": Sum("persistentvolumeclaim_capacity_byte_seconds"),
            "volume_request_storage_byte_seconds": Sum("volume_request_storage_byte_seconds"),
            "persistentvolumeclaim_usage_byte_seconds": Sum("persistentvolumeclaim_usage_byte_seconds"),
            "cluster_id": F("report_period__cluster_id"),
            "cluster_alias": Value(self.cluster_alias, output_field=CharField()),
        }
        entries = OCPStorageLineItem.objects.values(*included_fields).annotate(**annotations)

        for entry in entries:
            entry["total_seconds"] = 3600
            daily = OCPStorageLineItemDaily(**entry)
            daily.save() 
Example 21
Project: koku   Author: project-koku   File: helpers.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def _populate_node_label_daily_table(self):
        """Populate the daily table."""
        included_fields = ["node", "report_period_id", "node_labels"]
        annotations = {
            "usage_start": F("report__interval_start"),
            "usage_end": F("report__interval_start"),
            "cluster_id": F("report_period__cluster_id"),
            "cluster_alias": Value(self.cluster_alias, output_field=CharField()),
        }
        entries = OCPNodeLabelLineItem.objects.values(*included_fields).annotate(**annotations)

        for entry in entries:
            entry["total_seconds"] = 3600
            daily = OCPNodeLabelLineItemDaily(**entry)
            daily.save() 
Example 22
Project: koku   Author: project-koku   File: ocp_report_db_accessor.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def populate_markup_cost(self, markup, start_date, end_date, cluster_id):
        """Set markup cost for OCP including infrastructure cost markup."""
        with schema_context(self.schema):
            OCPUsageLineItemDailySummary.objects.filter(
                cluster_id=cluster_id, usage_start__gte=start_date, usage_start__lte=end_date
            ).update(
                infrastructure_markup_cost=(
                    (Coalesce(F("infrastructure_raw_cost"), Value(0, output_field=DecimalField()))) * markup
                ),
                infrastructure_project_markup_cost=(
                    (Coalesce(F("infrastructure_project_raw_cost"), Value(0, output_field=DecimalField()))) * markup
                ),
            ) 
Example 23
Project: timed-backend   Author: adfinis-sygroup   File: filters.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def filter_date(self, queryset, name, value):
        queryset = queryset.annotate(end=Coalesce("end_date", Value(date.today())))

        queryset = queryset.filter(start_date__lte=value, end__gte=value)

        return queryset 
Example 24
Project: timed-backend   Author: adfinis-sygroup   File: serializers.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def validate(self, data):
        """Validate the employment as a whole.

        Ensure the end date is after the start date and there is only one
        active employment per user and there are no overlapping employments.

        :throws: django.core.exceptions.ValidationError
        :return: validated data
        :rtype:  dict
        """
        instance = self.instance
        start_date = data.get("start_date", instance and instance.start_date)
        end_date = data.get("end_date", instance and instance.end_date)
        if end_date and start_date >= end_date:
            raise ValidationError(_("The end date must be after the start date"))

        user = data.get("user", instance and instance.user)
        employments = models.Employment.objects.filter(user=user)
        # end date not set means employment is ending today
        end_date = end_date or date.today()
        employments = employments.annotate(
            end=Coalesce("end_date", Value(date.today()))
        )
        if instance:
            employments = employments.exclude(id=instance.id)

        if any([e.start_date <= end_date and start_date <= e.end for e in employments]):
            raise ValidationError(
                _("A user can't have multiple employments at the same time")
            )

        return data 
Example 25
Project: bioforum   Author: reBiocoder   File: base.py    License: MIT License 5 votes vote down vote up
def coalesce(self):
        # null on either side results in null for expression, wrap with coalesce
        c = self.copy()
        expressions = [
            Coalesce(expression, Value('')) for expression in c.get_source_expressions()
        ]
        c.set_source_expressions(expressions)
        return c 
Example 26
Project: bioforum   Author: reBiocoder   File: ranges.py    License: MIT License 5 votes vote down vote up
def process_rhs(self, compiler, connection):
        # Transform rhs value for db lookup.
        if isinstance(self.rhs, datetime.date):
            output_field = models.DateTimeField() if isinstance(self.rhs, datetime.datetime) else models.DateField()
            value = models.Value(self.rhs, output_field=output_field)
            self.rhs = value.resolve_expression(compiler.query)
        return super().process_rhs(compiler, connection) 
Example 27
Project: karrot-backend   Author: yunity   File: models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def with_conversation_access(self, user):
        # Note: this is needed if ConversationQuerySet.with_access is too slow
        # should contain the same logic
        return self.filter(
            Q(conversation__participants=user) |
            Q(conversation__group__groupmembership__user=user, conversation__group__isnull=False)
        ).annotate(
            has_conversation_access=Value(True, output_field=models.BooleanField())
            # This is not just an annotation, we use it because it results in a 'group by' clause
            # It is much faster then the alternative 'distinct' modifier
        ) 
Example 28
Project: pasportaservo   Author: tejoesperanto   File: models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def mark_invalid_emails(cls, emails=None):
        """
        Adds the 'invalid' marker to all email addresses in the given list.
        """
        models = {cls: None, get_user_model(): None}
        for model in models:
            models[model] = (
                model.objects
                .filter(email__in=emails)
                .exclude(email='')
                .exclude(email__startswith=settings.INVALID_PREFIX)
                .update(email=Concat(V(settings.INVALID_PREFIX), F('email')))
            )
        return models 
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)),
    ))