Python django.db.models.expressions.Expression() Examples

The following are 8 code examples of django.db.models.expressions.Expression(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module django.db.models.expressions , or try the search function .
Example #1
Source File: lookups.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def process_rhs(self, compiler, connection):
        rhs, rhs_params = super(GISLookup, self).process_rhs(compiler, connection)
        if hasattr(self.rhs, '_as_sql'):
            # If rhs is some QuerySet, don't touch it
            return rhs, rhs_params

        geom = self.rhs
        if isinstance(self.rhs, Col):
            # Make sure the F Expression destination field exists, and
            # set an `srid` attribute with the same as that of the
            # destination.
            geo_fld = self.rhs.output_field
            if not hasattr(geo_fld, 'srid'):
                raise ValueError('No geographic field found in expression.')
            self.rhs.srid = geo_fld.srid
        elif isinstance(self.rhs, Expression):
            raise ValueError('Complex expressions not supported for GeometryField')
        elif isinstance(self.rhs, (list, tuple)):
            geom = self.rhs[0]
        rhs = connection.ops.get_geom_placeholder(self.lhs.output_field, geom, compiler)
        return rhs, rhs_params 
Example #2
Source File: lookups.py    From openhgsenti with Apache License 2.0 6 votes vote down vote up
def process_rhs(self, compiler, connection):
        rhs, rhs_params = super(GISLookup, self).process_rhs(compiler, connection)
        if hasattr(self.rhs, '_as_sql'):
            # If rhs is some QuerySet, don't touch it
            return rhs, rhs_params

        geom = self.rhs
        if isinstance(self.rhs, Col):
            # Make sure the F Expression destination field exists, and
            # set an `srid` attribute with the same as that of the
            # destination.
            geo_fld = self.rhs.output_field
            if not hasattr(geo_fld, 'srid'):
                raise ValueError('No geographic field found in expression.')
            self.rhs.srid = geo_fld.srid
        elif isinstance(self.rhs, Expression):
            raise ValueError('Complex expressions not supported for GeometryField')
        elif isinstance(self.rhs, (list, tuple)):
            geom = self.rhs[0]
        rhs = connection.ops.get_geom_placeholder(self.lhs.output_field, geom, compiler)
        return rhs, rhs_params 
Example #3
Source File: hstore_field.py    From django-postgres-extra with MIT License 6 votes vote down vote up
def get_prep_value(self, value):
        """Override the base class so it doesn't cast all values to strings.

        psqlextra supports expressions in hstore fields, so casting all
        values to strings is a bad idea.
        """

        value = Field.get_prep_value(self, value)

        if isinstance(value, dict):
            prep_value = {}
            for key, val in value.items():
                if isinstance(val, Expression):
                    prep_value[key] = val
                elif val is not None:
                    prep_value[key] = str(val)
                else:
                    prep_value[key] = val

            value = prep_value

        if isinstance(value, list):
            value = [str(item) for item in value]

        return value 
Example #4
Source File: fields.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_prep_value(self, value):
        """
        Spatial lookup values are either a parameter that is (or may be
        converted to) a geometry, or a sequence of lookup values that
        begins with a geometry.  This routine will setup the geometry
        value properly, and preserve any other lookup parameters before
        returning to the caller.
        """
        value = super(GeometryField, self).get_prep_value(value)
        if isinstance(value, Expression):
            return value
        elif isinstance(value, (tuple, list)):
            geom = value[0]
            seq_value = True
        else:
            geom = value
            seq_value = False

        # When the input is not a GEOS geometry, attempt to construct one
        # from the given string input.
        if isinstance(geom, Geometry):
            pass
        elif isinstance(geom, (bytes, six.string_types)) or hasattr(geom, '__geo_interface__'):
            try:
                geom = Geometry(geom)
            except GeometryException:
                raise ValueError('Could not create geometry from lookup value.')
        else:
            raise ValueError('Cannot use object with type %s for a geometry lookup parameter.' % type(geom).__name__)

        # Assigning the SRID value.
        geom.srid = self.get_srid(geom)

        if seq_value:
            lookup_val = [geom]
            lookup_val.extend(value[1:])
            return tuple(lookup_val)
        else:
            return geom 
Example #5
Source File: fields.py    From GTDWeb with GNU General Public License v2.0 5 votes vote down vote up
def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
        """
        Prepare for the database lookup, and return any spatial parameters
        necessary for the query.  This includes wrapping any geometry
        parameters with a backend-specific adapter and formatting any distance
        parameters into the correct units for the coordinate system of the
        field.
        """
        # special case for isnull lookup
        if lookup_type == 'isnull':
            return []
        elif lookup_type in self.class_lookups:
            # Populating the parameters list, and wrapping the Geometry
            # with the Adapter of the spatial backend.
            if isinstance(value, (tuple, list)):
                params = [connection.ops.Adapter(value[0])]
                if self.class_lookups[lookup_type].distance:
                    # Getting the distance parameter in the units of the field.
                    params += self.get_distance(value[1:], lookup_type, connection)
                elif lookup_type in connection.ops.truncate_params:
                    # Lookup is one where SQL parameters aren't needed from the
                    # given lookup value.
                    pass
                else:
                    params += value[1:]
            elif isinstance(value, Expression):
                params = []
            else:
                params = [connection.ops.Adapter(value)]

            return params
        else:
            raise ValueError('%s is not a valid spatial lookup for %s.' %
                             (lookup_type, self.__class__.__name__)) 
Example #6
Source File: fields.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_prep_value(self, value):
        """
        Spatial lookup values are either a parameter that is (or may be
        converted to) a geometry, or a sequence of lookup values that
        begins with a geometry.  This routine will setup the geometry
        value properly, and preserve any other lookup parameters before
        returning to the caller.
        """
        value = super(GeometryField, self).get_prep_value(value)
        if isinstance(value, Expression):
            return value
        elif isinstance(value, (tuple, list)):
            geom = value[0]
            seq_value = True
        else:
            geom = value
            seq_value = False

        # When the input is not a GEOS geometry, attempt to construct one
        # from the given string input.
        if isinstance(geom, Geometry):
            pass
        elif isinstance(geom, (bytes, six.string_types)) or hasattr(geom, '__geo_interface__'):
            try:
                geom = Geometry(geom)
            except GeometryException:
                raise ValueError('Could not create geometry from lookup value.')
        else:
            raise ValueError('Cannot use object with type %s for a geometry lookup parameter.' % type(geom).__name__)

        # Assigning the SRID value.
        geom.srid = self.get_srid(geom)

        if seq_value:
            lookup_val = [geom]
            lookup_val.extend(value[1:])
            return tuple(lookup_val)
        else:
            return geom 
Example #7
Source File: fields.py    From openhgsenti with Apache License 2.0 5 votes vote down vote up
def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
        """
        Prepare for the database lookup, and return any spatial parameters
        necessary for the query.  This includes wrapping any geometry
        parameters with a backend-specific adapter and formatting any distance
        parameters into the correct units for the coordinate system of the
        field.
        """
        # special case for isnull lookup
        if lookup_type == 'isnull':
            return []
        elif lookup_type in self.class_lookups:
            # Populating the parameters list, and wrapping the Geometry
            # with the Adapter of the spatial backend.
            if isinstance(value, (tuple, list)):
                params = [connection.ops.Adapter(value[0])]
                if self.class_lookups[lookup_type].distance:
                    # Getting the distance parameter in the units of the field.
                    params += self.get_distance(value[1:], lookup_type, connection)
                elif lookup_type in connection.ops.truncate_params:
                    # Lookup is one where SQL parameters aren't needed from the
                    # given lookup value.
                    pass
                else:
                    params += value[1:]
            elif isinstance(value, Expression):
                params = []
            else:
                params = [connection.ops.Adapter(value)]

            return params
        else:
            raise ValueError('%s is not a valid spatial lookup for %s.' %
                             (lookup_type, self.__class__.__name__)) 
Example #8
Source File: utils.py    From Dailyfresh-B2C with Apache License 2.0 4 votes vote down vote up
def resolve_field(model_field, lookup_expr):
    """
    Resolves a ``lookup_expr`` into its final output field, given
    the initial ``model_field``. The lookup expression should only contain
    transforms and lookups, not intermediary model field parts.

    Note:
    This method is based on django.db.models.sql.query.Query.build_lookup

    For more info on the lookup API:
    https://docs.djangoproject.com/en/1.9/ref/models/lookups/

    """
    query = model_field.model._default_manager.all().query
    lhs = Expression(model_field)
    lookups = lookup_expr.split(LOOKUP_SEP)

    assert len(lookups) > 0

    try:
        while lookups:
            name = lookups[0]
            args = (lhs, name)
            if django.VERSION < (2, 0):
                # rest_of_lookups was removed in Django 2.0
                args += (lookups,)
            # If there is just one part left, try first get_lookup() so
            # that if the lhs supports both transform and lookup for the
            # name, then lookup will be picked.
            if len(lookups) == 1:
                final_lookup = lhs.get_lookup(name)
                if not final_lookup:
                    # We didn't find a lookup. We are going to interpret
                    # the name as transform, and do an Exact lookup against
                    # it.
                    lhs = query.try_transform(*args)
                    final_lookup = lhs.get_lookup('exact')
                return lhs.output_field, final_lookup.lookup_name
            lhs = query.try_transform(*args)
            lookups = lookups[1:]
    except FieldError as e:
        six.raise_from(FieldLookupError(model_field, lookup_expr), e)