Python django.db.models.Func() Examples

The following are 19 code examples for showing how to use django.db.models.Func(). 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
def clean_domain_name(field_name):
    """
    Returns a Django query expression that replaces all underscores with a
    hyphen, removes leading and trailing hyphens, and converts the field to
    lower case.
    """
    remove_underscores = Func(
        F(field_name),
        Value('_'),
        Value('-'),
        function='replace'
    )
    trim_hyphens = Func(
        remove_underscores,
        Value('-'),
        function='btrim',
    )
    remove_trailing_hyphens = Func(
        trim_hyphens,
        Value(r'[-]+\.'),
        Value('.'),
        Value('g'),
        function='regexp_replace'
    )
    return Lower(remove_trailing_hyphens) 
Example 2
Project: YaraGuardian   Author: PUNCH-Cyber   File: managers.py    License: Apache License 2.0 6 votes vote down vote up
def change_metakey_case(self, metakey, operation, modifier=None):
        available_operations = {'lowercase': lowercase,
                                'uppercase': uppercase,
                                'capitalize': capitalize}

        edit = available_operations.get(operation, None)

        if edit:

            if modifier:
                new_metakey = metakey.replace(modifier, edit(modifier))
            else:
                new_metakey = edit(metakey)

            # Copy old metadata into an hstore container with new key value
            TEMP_HSTORE = Func(Value(new_metakey), GET_VALUE('metadata') + Value(metakey), function='hstore')

            # Delete old key entry from original hstore
            META_HSTORE = Func(F('metadata'), Value(metakey), function='delete')

            # Combine the two hstores using internal 'hs_concat' function
            CONCAT_HSTORE = Func(TEMP_HSTORE, META_HSTORE, function='hs_concat')

            self.filter(metadata__has_key=metakey).update(metadata=CONCAT_HSTORE) 
Example 3
Project: YaraGuardian   Author: PUNCH-Cyber   File: managers.py    License: Apache License 2.0 6 votes vote down vote up
def set_metadata(self, metakey, metavalue):

        if check_lexical_convention(metakey) and \
        (metavalue.isdigit() or metavalue in ('true', 'false') or \
        (metavalue.startswith('\"') and metavalue.endswith('\"'))):

            # Copy old metadata into an hstore container with new key value
            TEMP_HSTORE = Func(Value(metakey), Value(metavalue), function='hstore')

            # Delete old key entry from original hstore
            META_HSTORE = Func(F('metadata'), Value(metakey), function='delete')

            # Combine the two hstores using internal 'hs_concat' function
            CONCAT_HSTORE = Func(TEMP_HSTORE, META_HSTORE, function='hs_concat')

            self.update(metadata=CONCAT_HSTORE) 
Example 4
Project: openprescribing   Author: ebmdatalab   File: infer_practice_boundaries.py    License: MIT License 6 votes vote down vote up
def infer_practice_boundaries():
    practices = Practice.objects.filter(location__isnull=False, setting=4).exclude(
        status_code__in=(
            Practice.STATUS_RETIRED,
            Practice.STATUS_DORMANT,
            Practice.STATUS_CLOSED,
        )
    )
    partition = practices.aggregate(
        voronoi=Func(Collect("location"), function="ST_VoronoiPolygons")
    )["voronoi"]
    national_boundary = get_national_boundary()
    practice_regions = get_practice_code_to_region_map(partition, national_boundary)
    with transaction.atomic():
        for practice in practices:
            practice.boundary = practice_regions[practice.code]
            practice.save(update_fields=["boundary"]) 
Example 5
Project: bioforum   Author: reBiocoder   File: base.py    License: MIT License 5 votes vote down vote up
def as_oracle(self, compiler, connection):
        # we can't mix TextField (NCLOB) and CharField (NVARCHAR), so convert
        # all fields to NCLOB when we expect NCLOB
        if self.output_field.get_internal_type() == 'TextField':
            class ToNCLOB(Func):
                function = 'TO_NCLOB'

            expressions = [
                ToNCLOB(expression) for expression in self.get_source_expressions()]
            clone = self.copy()
            clone.set_source_expressions(expressions)
            return super(Coalesce, clone).as_sql(compiler, connection)
        return self.as_sql(compiler, connection) 
Example 6
def populate_date_range(apps, schema_editor):
    Activity = apps.get_model('activities', 'Activity')

    # initializes the date_range field with a range of (date, date + 30 minutes)
    Activity.objects.all().update(
        date_range=Func(F('date'), F('date') + timedelta(minutes=30), function='tstzrange')
    ) 
Example 7
Project: mangaki   Author: mangaki   File: models.py    License: GNU Affero General Public License v3.0 5 votes vote down vote up
def __init__(self, lhs, rhs):
        super().__init__(Func(Func(lhs, function='F_UNACCENT'), function='UPPER'), Func(Func(rhs, function='F_UNACCENT'), function='UPPER')) 
Example 8
Project: django-rdkit   Author: rdkit   File: fields.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_prep_value(self, value):
        # convert the Molecule instance to the value used by the
        # db driver
        if isinstance(value, str):
            value = self.text_to_mol(value)
        if isinstance(value, Chem.Mol):
            value = memoryview(value.ToBinary())
        if value is None:
            return None
        return Func(value, function='mol_from_pkl') 
Example 9
Project: Hands-On-Application-Development-with-PyCharm   Author: PacktPublishing   File: comparison.py    License: MIT License 5 votes vote down vote up
def as_oracle(self, compiler, connection):
        # Oracle prohibits mixing TextField (NCLOB) and CharField (NVARCHAR2),
        # so convert all fields to NCLOB when that type is expected.
        if self.output_field.get_internal_type() == 'TextField':
            class ToNCLOB(Func):
                function = 'TO_NCLOB'

            expressions = [
                ToNCLOB(expression) for expression in self.get_source_expressions()
            ]
            clone = self.copy()
            clone.set_source_expressions(expressions)
            return super(Coalesce, clone).as_sql(compiler, connection)
        return self.as_sql(compiler, connection) 
Example 10
Project: zentral   Author: zentralopensource   File: models.py    License: Apache License 2.0 5 votes vote down vote up
def current_event_types(self):
        qs = (ProbeSource.objects.annotate(event_type=Func(F("event_types"), function="unnest"))
                                 .values("event_type").distinct().order_by())
        return sorted(((rd["event_type"], event_types[rd["event_type"]].get_event_type_display())
                       for rd in qs),
                      key=lambda t: t[1]) 
Example 11
Project: python   Author: Yeah-Kun   File: base.py    License: Apache License 2.0 5 votes vote down vote up
def as_oracle(self, compiler, connection):
        # we can't mix TextField (NCLOB) and CharField (NVARCHAR), so convert
        # all fields to NCLOB when we expect NCLOB
        if self.output_field.get_internal_type() == 'TextField':
            class ToNCLOB(Func):
                function = 'TO_NCLOB'

            expressions = [
                ToNCLOB(expression) for expression in self.get_source_expressions()]
            clone = self.copy()
            clone.set_source_expressions(expressions)
            return super(Coalesce, clone).as_sql(compiler, connection)
        return self.as_sql(compiler, connection) 
Example 12
Project: python2017   Author: bpgc-cte   File: base.py    License: MIT License 5 votes vote down vote up
def as_oracle(self, compiler, connection):
        # we can't mix TextField (NCLOB) and CharField (NVARCHAR), so convert
        # all fields to NCLOB when we expect NCLOB
        if self.output_field.get_internal_type() == 'TextField':
            class ToNCLOB(Func):
                function = 'TO_NCLOB'

            expressions = [
                ToNCLOB(expression) for expression in self.get_source_expressions()]
            clone = self.copy()
            clone.set_source_expressions(expressions)
            return super(Coalesce, clone).as_sql(compiler, connection)
        return self.as_sql(compiler, connection) 
Example 13
Project: django-bulk-update   Author: aykut   File: tests.py    License: MIT License 5 votes vote down vote up
def test_Func_expresion(self):

        # initialize
        ini_values = 'aA', 'BB', '', 'cc', '12'
        people = Person.objects.order_by('pk').all()
        for value, person in zip(ini_values, people):
            person.name = value
            person.text = value*2
            person.save()

        # set
        people = Person.objects.order_by('pk').all()
        for person in people:
            person.name = Func(F('name'), function='UPPER')
            person.text = Func(F('text'), function='LOWER')

        # update
        Person.objects.bulk_update(people)

        # check
        people = Person.objects.order_by('pk').all()

        expected_values = 'AA', 'BB', '', 'CC', '12'
        for expected_value, person in zip(expected_values, people):
            saved_value = person.name
            self.assertEqual(saved_value, expected_value)

        expected_values = 'aaaa', 'bbbb', '', 'cccc', '1212'
        for expected_value, person in zip(expected_values, people):
            saved_value = person.text
            self.assertEqual(saved_value, expected_value) 
Example 14
Project: django-bulk-update   Author: aykut   File: tests.py    License: MIT License 5 votes vote down vote up
def test_already_evaluated_queryset(self):
        """
        Queries:
            - update objects

        (objects are already retrieved, because of the previous loop)
        """
        people = Person.objects.all()
        for person in people:
            person.age += 2
            person.name = Func(F('name'), function='UPPER')
            person.text = 'doc'
            person.height -= Decimal(0.5)
        self.assertNumQueries(1, Person.objects.bulk_update, people) 
Example 15
Project: sfm-ui   Author: gwu-libraries   File: models.py    License: MIT License 5 votes vote down vote up
def move_collection_receiver(sender, **kwargs):
    """
    A post_save receiver that is triggered when Collection model objects are changed.
    """
    if kwargs["created"]:
        return
    collection = kwargs["instance"]
    try:
        prev_collection = collection.history.all()[1]
    except IndexError:
        return
    if collection.collection_set != prev_collection.collection_set:
        src_collection_path = get_collection_path(prev_collection)
        dest_collection_path = get_collection_path(collection)
        if not os.path.exists(src_collection_path):
            log.warn("Not moving collection directory since %s does not exist", src_collection_path)
            return
        if os.path.exists(dest_collection_path):
            log.error("Cannot move collection directory %s since %s already exists")
            return
        log.info("Moving %s to %s", src_collection_path, dest_collection_path)
        shutil.move(src_collection_path, dest_collection_path)
        # Update WARC model objects
        Warc.objects.filter(harvest__collection=collection).update(
            path=Func(
                F('path'),
                Value(src_collection_path), Value(dest_collection_path),
                function='replace',
            )
        ) 
Example 16
Project: YaraGuardian   Author: PUNCH-Cyber   File: managers.py    License: Apache License 2.0 5 votes vote down vote up
def rename_metakey(self, old_metakey, new_metakey):

        if check_lexical_convention(new_metakey):
            # Copy old metadata into an hstore container with new key value
            TEMP_HSTORE = Func(Value(new_metakey), GET_VALUE('metadata') + Value(old_metakey), function='hstore')

            # Delete old key entry from original hstore
            META_HSTORE = Func(F('metadata'), Value(old_metakey), function='delete')

            # Combine the two hstores using internal 'hs_concat' function
            CONCAT_HSTORE = Func(TEMP_HSTORE, META_HSTORE, function='hs_concat')

            self.filter(metadata__has_key=old_metakey).update(metadata=CONCAT_HSTORE) 
Example 17
Project: openprescribing   Author: ebmdatalab   File: managers.py    License: MIT License 5 votes vote down vote up
def _divide(numerator_field, denominator_field):
    """
    SQL division function which handles NULLs and divide-by-zero gracefully
    """
    numerator = Coalesce(numerator_field, Value(0.0))
    denominator = Func(denominator_field, Value(0.0), function="NULLIF")
    return numerator / denominator 
Example 18
Project: openprescribing   Author: ebmdatalab   File: managers.py    License: MIT License 5 votes vote down vote up
def _build_json_object(dictionary):
    """
    SQL function which builds a JSONB object from a Python dictionary whose
    keys are fixed values (strings or ints) but whose values may be arbitrary
    SQL functions
    """
    args = []
    for key, value in dictionary.items():
        args.append(Value(_preserve_key_type(key)))
        args.append(value)
    return Func(*args, function="jsonb_build_object", output_field=JSONField()) 
Example 19
Project: koku   Author: project-koku   File: tests_queries.py    License: GNU Affero General Public License v3.0 4 votes vote down vote up
def test_execute_query_with_counts(self):
        """Test execute_query with counts of unique resources."""
        url = "?compute_count=true&filter[time_scope_units]=month&filter[time_scope_value]=-1&filter[resolution]=daily&group_by[instance_type]=*"  # noqa: E501
        query_params = self.mocked_query_params(url, AWSInstanceTypeView)
        handler = AWSReportQueryHandler(query_params)
        query_output = handler.execute_query()
        data = query_output.get("data")
        self.assertIsNotNone(data)
        self.assertIsNotNone(query_output.get("total"))

        total = query_output.get("total")
        self.assertIsNotNone(total.get("count"))

        annotations = {
            "date": F("usage_start"),
            "type": F("instance_type"),
            "resource_id": Func(F("resource_ids"), function="unnest"),
        }

        with tenant_context(self.tenant):
            expected_counts = (
                AWSCostEntryLineItemDailySummary.objects.filter(
                    instance_type__isnull=False, usage_start__gte=self.dh.this_month_start
                )
                .values(**annotations)
                .distinct()
            )

            total_count = (
                AWSCostEntryLineItemDailySummary.objects.filter(
                    instance_type__isnull=False, usage_start__gte=self.dh.this_month_start
                )
                .values(**{"resource_id": Func(F("resource_ids"), function="unnest")})
                .distinct()
                .count()
            )

            count_dict = defaultdict(dict)
            for item in expected_counts:
                if "i-" in item["resource_id"]:
                    if item["type"] in count_dict[str(item["date"])]:
                        count_dict[str(item["date"])][item["type"]] += 1
                    else:
                        count_dict[str(item["date"])][item["type"]] = 1

        for data_item in data:
            instance_types = data_item.get("instance_types")
            for it in instance_types:
                expected_count = count_dict.get(data_item.get("date")).get(it["instance_type"])
                actual_count = it["values"][0].get("count", {}).get("value", 0)
                self.assertEqual(actual_count, expected_count)
        self.assertEqual(total.get("count", {}).get("value"), total_count)