desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Helper function that returns the database column for the given field. The table and column are returned (quoted) in the proper format, e.g., `"geoapp_city"."point"`. If `table_alias` is not specified, the database table associated with the model of this `GeoQuery` will be used. If `column` is specified, it will be used instead of the value in `field.column`.'
def _field_column(self, field, table_alias=None, column=None):
if (table_alias is None): table_alias = self.query.model._meta.db_table return ('%s.%s' % (self.quote_name_unless_alias(table_alias), self.connection.ops.quote_name((column or field.column))))
'Returns the geometry database type for Oracle. Unlike other spatial backends, no stored procedure is necessary and it\'s the same for all geometry types.'
def geo_db_type(self, f):
return 'MDSYS.SDO_GEOMETRY'
'Returns the distance parameters given the value and the lookup type. On Oracle, geometry columns with a geodetic coordinate system behave implicitly like a geography column, and thus meters will be used as the distance parameter on them.'
def get_distance(self, f, value, lookup_type):
if (not value): return [] value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): dist_param = value.m else: dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection))) else: dist_param = value if (lookup_type == 'dwithin'): dist_param = ('distance=%s' % dist_param) return [dist_param]
'Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the SDO_CS.TRANSFORM() function call.'
def get_geom_placeholder(self, f, value):
if (value is None): return 'NULL' def transform_value(val, srid): return (val.srid != srid) if hasattr(value, 'expression'): if transform_value(value, f.srid): placeholder = ('%s(%%s, %s)' % (self.transform, f.srid)) else: placeholder = '%s' return (placeholder % self.get_expression_column(value)) elif transform_value(value, f.srid): return ('%s(SDO_GEOMETRY(%%s, %s), %s)' % (self.transform, value.srid, f.srid)) else: return ('SDO_GEOMETRY(%%s, %s)' % f.srid)
'Returns the SQL WHERE clause for use in Oracle spatial SQL construction.'
def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn):
(alias, col, db_type) = lvalue geo_col = ('%s.%s' % (qn(alias), qn(col))) lookup_info = self.geometry_functions.get(lookup_type, False) if lookup_info: if isinstance(lookup_info, tuple): (sdo_op, arg_type) = lookup_info geom = value[0] if (not isinstance(value, tuple)): raise ValueError(('Tuple required for `%s` lookup type.' % lookup_type)) if (len(value) != 2): raise ValueError(('2-element tuple required for %s lookup type.' % lookup_type)) if (not isinstance(value[1], arg_type)): raise ValueError(('Argument type should be %s, got %s instead.' % (arg_type, type(value[1])))) if (lookup_type == 'relate'): return sdo_op(value[1]).as_sql(geo_col, self.get_geom_placeholder(field, geom)) else: return sdo_op.as_sql(geo_col, self.get_geom_placeholder(field, geom)) else: return lookup_info.as_sql(geo_col, self.get_geom_placeholder(field, value)) elif (lookup_type == 'isnull'): return ('%s IS %sNULL' % (geo_col, (((not value) and 'NOT ') or ''))) raise TypeError(('Got invalid lookup_type: %s' % repr(lookup_type)))
'Returns the spatial aggregate SQL template and function for the given Aggregate instance.'
def spatial_aggregate_sql(self, agg):
agg_name = agg.__class__.__name__.lower() if (agg_name == 'union'): agg_name += 'agg' if agg.is_extent: sql_template = '%(function)s(%(field)s)' else: sql_template = '%(function)s(SDOAGGRTYPE(%(field)s,%(tolerance)s))' sql_function = getattr(self, agg_name) return ((self.select % sql_template), sql_function)
'Drop out insert parameters for NULL placeholder. Needed for Oracle Spatial backend due to #10888'
def modify_insert_params(self, placeholders, params):
assert (len(placeholders) == 1) return [[param for (pholder, param) in six.moves.zip(placeholders[0], params[0]) if (pholder != 'NULL')]]
'Returns the name of the metadata column used to store the the feature table name.'
@classmethod def table_name_col(cls):
return 'table_name'
'Returns the name of the metadata column used to store the the feature geometry column.'
@classmethod def geom_col_name(cls):
return 'column_name'
'Return any spatial index creation SQL for the field.'
def sql_indexes_for_field(self, model, f, style):
from django.contrib.gis.db.models.fields import GeometryField output = super(OracleCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField): gqn = self.connection.ops.geo_quote_name qn = self.connection.ops.quote_name db_table = model._meta.db_table output.append((((((((((((((((style.SQL_KEYWORD('INSERT INTO ') + style.SQL_TABLE('USER_SDO_GEOM_METADATA')) + (' (%s, %s, %s, %s)\n ' % tuple(map(qn, ['TABLE_NAME', 'COLUMN_NAME', 'DIMINFO', 'SRID'])))) + style.SQL_KEYWORD(' VALUES ')) + '(\n ') + style.SQL_TABLE(gqn(db_table))) + ',\n ') + style.SQL_FIELD(gqn(f.column))) + ',\n ') + style.SQL_KEYWORD('MDSYS.SDO_DIM_ARRAY')) + '(\n ') + style.SQL_KEYWORD('MDSYS.SDO_DIM_ELEMENT')) + ("('LONG', %s, %s, %s),\n " % (f._extent[0], f._extent[2], f._tolerance))) + style.SQL_KEYWORD('MDSYS.SDO_DIM_ELEMENT')) + ("('LAT', %s, %s, %s)\n ),\n" % (f._extent[1], f._extent[3], f._tolerance))) + (' %s\n );' % f.srid))) if f.spatial_index: idx_name = truncate_name(('%s_%s_id' % (db_table, f.column)), 30) output.append((((((((((style.SQL_KEYWORD('CREATE INDEX ') + style.SQL_TABLE(qn(idx_name))) + style.SQL_KEYWORD(' ON ')) + style.SQL_TABLE(qn(db_table))) + '(') + style.SQL_FIELD(qn(f.column))) + ') ') + style.SQL_KEYWORD('INDEXTYPE IS ')) + style.SQL_TABLE('MDSYS.SPATIAL_INDEX')) + ';')) return output
'Returns the database column type for the geometry field on the spatial backend.'
def geo_db_type(self, f):
raise NotImplementedError
'Returns the distance parameters for the given geometry field, lookup value, and lookup type.'
def get_distance(self, f, value, lookup_type):
raise NotImplementedError('Distance operations not available on this spatial backend.')
'Returns the placeholder for the given geometry field with the given value. Depending on the spatial backend, the placeholder may contain a stored procedure call to the transformation function of the spatial backend.'
def get_geom_placeholder(self, f, value):
raise NotImplementedError
'Helper method to return the quoted column string from the evaluator for its expression.'
def get_expression_column(self, evaluator):
for (expr, col_tup) in evaluator.cols: if (expr is evaluator.expression): return ('%s.%s' % tuple(map(self.quote_name, col_tup))) raise Exception('Could not find the column for the expression.')
'Returns a GDAL SpatialReference object, if GDAL is installed.'
@property def srs(self):
if gdal.HAS_GDAL: if hasattr(self, '_srs'): return self._srs.clone() else: try: self._srs = gdal.SpatialReference(self.wkt) return self.srs except Exception as msg: pass try: self._srs = gdal.SpatialReference(self.proj4text) return self.srs except Exception as msg: pass raise Exception(('Could not get OSR SpatialReference from WKT: %s\nError:\n%s' % (self.wkt, msg))) else: raise Exception('GDAL is not installed.')
'Returns a tuple of the ellipsoid parameters: (semimajor axis, semiminor axis, and inverse flattening).'
@property def ellipsoid(self):
if gdal.HAS_GDAL: return self.srs.ellipsoid else: m = self.spheroid_regex.match(self.wkt) if m: return (float(m.group('major')), float(m.group('flattening'))) else: return None
'Returns the projection name.'
@property def name(self):
return self.srs.name
'Returns the spheroid name for this spatial reference.'
@property def spheroid(self):
return self.srs['spheroid']
'Returns the datum for this spatial reference.'
@property def datum(self):
return self.srs['datum']
'Is this Spatial Reference projected?'
@property def projected(self):
if gdal.HAS_GDAL: return self.srs.projected else: return self.wkt.startswith('PROJCS')
'Is this Spatial Reference local?'
@property def local(self):
if gdal.HAS_GDAL: return self.srs.local else: return self.wkt.startswith('LOCAL_CS')
'Is this Spatial Reference geographic?'
@property def geographic(self):
if gdal.HAS_GDAL: return self.srs.geographic else: return self.wkt.startswith('GEOGCS')
'Returns the linear units name.'
@property def linear_name(self):
if gdal.HAS_GDAL: return self.srs.linear_name elif self.geographic: return None else: m = self.units_regex.match(self.wkt) return m.group('unit_name')
'Returns the linear units.'
@property def linear_units(self):
if gdal.HAS_GDAL: return self.srs.linear_units elif self.geographic: return None else: m = self.units_regex.match(self.wkt) return m.group('unit')
'Returns the name of the angular units.'
@property def angular_name(self):
if gdal.HAS_GDAL: return self.srs.angular_name elif self.projected: return None else: m = self.units_regex.match(self.wkt) return m.group('unit_name')
'Returns the angular units.'
@property def angular_units(self):
if gdal.HAS_GDAL: return self.srs.angular_units elif self.projected: return None else: m = self.units_regex.match(self.wkt) return m.group('unit')
'Returns a tuple of the units and the name.'
@property def units(self):
if (self.projected or self.local): return (self.linear_units, self.linear_name) elif self.geographic: return (self.angular_units, self.angular_name) else: return (None, None)
'Class method used by GeometryField on initialization to retrive the units on the given WKT, without having to use any of the database fields.'
@classmethod def get_units(cls, wkt):
if gdal.HAS_GDAL: return gdal.SpatialReference(wkt).units else: m = cls.units_regex.match(wkt) return (m.group('unit'), m.group('unit_name'))
'Class method used by GeometryField on initialization to retrieve the `SPHEROID[..]` parameters from the given WKT.'
@classmethod def get_spheroid(cls, wkt, string=True):
if gdal.HAS_GDAL: srs = gdal.SpatialReference(wkt) sphere_params = srs.ellipsoid sphere_name = srs['spheroid'] else: m = cls.spheroid_regex.match(wkt) if m: sphere_params = (float(m.group('major')), float(m.group('flattening'))) sphere_name = m.group('name') else: return None if (not string): return (sphere_name, sphere_params) else: if (len(sphere_params) == 3): (radius, flattening) = (sphere_params[0], sphere_params[2]) else: (radius, flattening) = sphere_params return ('SPHEROID["%s",%s,%s]' % (sphere_name, radius, flattening))
'Returns the string representation. If GDAL is installed, it will be \'pretty\' OGC WKT.'
def __str__(self):
try: return six.text_type(self.srs) except: return six.text_type(self.wkt)
'Checks if the given aggregate name is supported (that is, if it\'s in `self.valid_aggregates`).'
def check_aggregate_support(self, aggregate):
agg_name = aggregate.__class__.__name__ return (agg_name in self.valid_aggregates)
'Returns a 4-tuple extent for the `Extent` aggregate by converting the bounding box text returned by PostGIS (`box` argument), for example: "BOX(-90.0 30.0, -85.0 40.0)".'
def convert_extent(self, box):
(ll, ur) = box[4:(-1)].split(',') (xmin, ymin) = map(float, ll.split()) (xmax, ymax) = map(float, ur.split()) return (xmin, ymin, xmax, ymax)
'Returns a 6-tuple extent for the `Extent3D` aggregate by converting the 3d bounding-box text returnded by PostGIS (`box3d` argument), for example: "BOX3D(-90.0 30.0 1, -85.0 40.0 2)".'
def convert_extent3d(self, box3d):
(ll, ur) = box3d[6:(-1)].split(',') (xmin, ymin, zmin) = map(float, ll.split()) (xmax, ymax, zmax) = map(float, ur.split()) return (xmin, ymin, zmin, xmax, ymax, zmax)
'Converts the geometry returned from PostGIS aggretates.'
def convert_geom(self, hex, geo_field):
if hex: return Geometry(hex) else: return None
'Return the database field type for the given geometry field. Typically this is `None` because geometry columns are added via the `AddGeometryColumn` stored procedure, unless the field has been specified to be of geography type instead.'
def geo_db_type(self, f):
if f.geography: if (not self.geography): raise NotImplementedError('PostGIS 1.5 required for geography column support.') if (f.srid != 4326): raise NotImplementedError('PostGIS 1.5 supports geography columns only with an SRID of 4326.') return ('geography(%s,%d)' % (f.geom_type, f.srid)) elif self.geometry: if (f.dim == 3): geom_type = (f.geom_type + 'Z') else: geom_type = f.geom_type return ('geometry(%s,%d)' % (geom_type, f.srid)) else: return None
'Retrieve the distance parameters for the given geometry field, distance lookup value, and the distance lookup type. This is the most complex implementation of the spatial backends due to what is supported on geodetic geometry columns vs. what\'s available on projected geometry columns. In addition, it has to take into account the newly introduced geography column type introudced in PostGIS 1.5.'
def get_distance(self, f, dist_val, lookup_type):
if (len(dist_val) == 1): (value, option) = (dist_val[0], None) else: (value, option) = dist_val geodetic = f.geodetic(self.connection) geography = (f.geography and self.geography) if isinstance(value, Distance): if geography: dist_param = value.m elif geodetic: if (lookup_type == 'dwithin'): raise ValueError('Only numeric values of degree units are allowed on geographic DWithin queries.') dist_param = value.m else: dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection))) else: dist_param = value if ((not geography) and geodetic and (lookup_type != 'dwithin') and (option == 'spheroid')): return [f._spheroid, dist_param] else: return [dist_param]
'Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the ST_Transform() function call.'
def get_geom_placeholder(self, f, value):
if ((value is None) or (value.srid == f.srid)): placeholder = '%s' else: placeholder = ('%s(%%s, %s)' % (self.transform, f.srid)) if hasattr(value, 'expression'): placeholder = (placeholder % self.get_expression_column(value)) return placeholder
'Helper routine for calling PostGIS functions and returning their result.'
def _get_postgis_func(self, func):
cursor = self.connection._cursor() try: cursor.execute(('SELECT %s()' % func)) row = cursor.fetchone() except: raise finally: self.connection.close() return row[0]
'Returns the version of the GEOS library used with PostGIS.'
def postgis_geos_version(self):
return self._get_postgis_func('postgis_geos_version')
'Returns the version number of the PostGIS library used with PostgreSQL.'
def postgis_lib_version(self):
return self._get_postgis_func('postgis_lib_version')
'Returns the version of the PROJ.4 library used with PostGIS.'
def postgis_proj_version(self):
return self._get_postgis_func('postgis_proj_version')
'Returns PostGIS version number and compile-time options.'
def postgis_version(self):
return self._get_postgis_func('postgis_version')
'Returns PostGIS version number and compile-time options.'
def postgis_full_version(self):
return self._get_postgis_func('postgis_full_version')
'Returns the PostGIS version as a tuple (version string, major, minor, subminor).'
def postgis_version_tuple(self):
version = self.postgis_lib_version() m = self.version_regex.match(version) if m: major = int(m.group('major')) minor1 = int(m.group('minor1')) minor2 = int(m.group('minor2')) else: raise Exception(('Could not parse PostGIS version string: %s' % version)) return (version, major, minor1, minor2)
'Return the version of PROJ.4 used by PostGIS as a tuple of the major, minor, and subminor release numbers.'
def proj_version_tuple(self):
proj_regex = re.compile('(\\d+)\\.(\\d+)\\.(\\d+)') proj_ver_str = self.postgis_proj_version() m = proj_regex.search(proj_ver_str) if m: return tuple(map(int, [m.group(1), m.group(2), m.group(3)])) else: raise Exception('Could not determine PROJ.4 version from PostGIS.')
'Helper routine that returns a boolean indicating whether the number of parameters is correct for the lookup type.'
def num_params(self, lookup_type, num_param):
def exactly_two(np): return (np == 2) def two_to_three(np): return ((np >= 2) and (np <= 3)) if ((lookup_type in self.distance_functions) and (lookup_type != 'dwithin')): return two_to_three(num_param) else: return exactly_two(num_param)
'Constructs spatial SQL from the given lookup value tuple a (alias, col, db_type), the lookup type string, lookup value, and the geometry field.'
def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn):
(alias, col, db_type) = lvalue geo_col = ('%s.%s' % (qn(alias), qn(col))) if (lookup_type in self.geometry_operators): if (field.geography and (not (lookup_type in self.geography_operators))): raise ValueError(('PostGIS geography does not support the "%s" lookup.' % lookup_type)) op = self.geometry_operators[lookup_type] return op.as_sql(geo_col, self.get_geom_placeholder(field, value)) elif (lookup_type in self.geometry_functions): if (field.geography and (not (lookup_type in self.geography_functions))): raise ValueError(('PostGIS geography type does not support the "%s" lookup.' % lookup_type)) tmp = self.geometry_functions[lookup_type] if isinstance(tmp, tuple): (op, arg_type) = tmp if (not isinstance(value, (tuple, list))): raise ValueError(('Tuple required for `%s` lookup type.' % lookup_type)) geom = value[0] nparams = len(value) if (not self.num_params(lookup_type, nparams)): raise ValueError(('Incorrect number of parameters given for `%s` lookup type.' % lookup_type)) if (not isinstance(value[1], arg_type)): raise ValueError(('Argument type should be %s, got %s instead.' % (arg_type, type(value[1])))) if (lookup_type == 'relate'): op = op(self.geom_func_prefix, value[1]) elif ((lookup_type in self.distance_functions) and (lookup_type != 'dwithin')): if ((not field.geography) and field.geodetic(self.connection)): if (not self.connection.ops.geography): if (field.geom_type != 'POINT'): raise ValueError('PostGIS spherical operations are only valid on PointFields.') if (str(geom.geom_type) != 'Point'): raise ValueError('PostGIS geometry distance parameter is required to be of type Point.') if ((nparams == 3) and (value[2] == 'spheroid')): op = op['spheroid'] else: op = op['sphere'] else: op = op['cartesian'] else: op = tmp geom = value return op.as_sql(geo_col, self.get_geom_placeholder(field, geom)) elif (lookup_type == 'isnull'): return ('%s IS %sNULL' % (geo_col, (((not value) and 'NOT ') or ''))) raise TypeError(('Got invalid lookup_type: %s' % repr(lookup_type)))
'Returns the spatial aggregate SQL template and function for the given Aggregate instance.'
def spatial_aggregate_sql(self, agg):
agg_name = agg.__class__.__name__ if (not self.check_aggregate_support(agg)): raise NotImplementedError(('%s spatial aggregate is not implmented for this backend.' % agg_name)) agg_name = agg_name.lower() if (agg_name == 'union'): agg_name += 'agg' sql_template = '%(function)s(%(field)s)' sql_function = getattr(self, agg_name) return (sql_template, sql_function)
'Returns the name of the metadata column used to store the the feature table name.'
@classmethod def table_name_col(cls):
return 'f_table_name'
'Returns the name of the metadata column used to store the the feature geometry column.'
@classmethod def geom_col_name(cls):
return 'f_geometry_column'
'Initializes on the geometry.'
def __init__(self, geom):
self.ewkb = bytes(geom.ewkb) self.srid = geom.srid self._adapter = Binary(self.ewkb)
'This method allows escaping the binary in the style required by the server\'s `standard_conforming_string` setting.'
def prepare(self, conn):
self._adapter.prepare(conn)
'Returns a properly quoted string for use in PostgreSQL/PostGIS.'
def getquoted(self):
return str((u'ST_GeomFromEWKB(%s)' % self._adapter.getquoted().decode()))
'Return any spatial index creation SQL for the field.'
def sql_indexes_for_field(self, model, f, style):
from django.contrib.gis.db.models.fields import GeometryField output = super(PostGISCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField): gqn = self.connection.ops.geo_quote_name qn = self.connection.ops.quote_name db_table = model._meta.db_table if (f.geography or self.connection.ops.geometry): pass else: output.append(((((((((((((style.SQL_KEYWORD('SELECT ') + style.SQL_TABLE('AddGeometryColumn')) + '(') + style.SQL_TABLE(gqn(db_table))) + ', ') + style.SQL_FIELD(gqn(f.column))) + ', ') + style.SQL_FIELD(str(f.srid))) + ', ') + style.SQL_COLTYPE(gqn(f.geom_type))) + ', ') + style.SQL_KEYWORD(str(f.dim))) + ');')) if (not f.null): output.append((((((style.SQL_KEYWORD('ALTER TABLE ') + style.SQL_TABLE(qn(db_table))) + style.SQL_KEYWORD(' ALTER ')) + style.SQL_FIELD(qn(f.column))) + style.SQL_KEYWORD(' SET NOT NULL')) + ';')) if f.spatial_index: if f.geography: index_ops = '' elif self.connection.ops.geometry: if (f.dim > 2): index_ops = (' ' + style.SQL_KEYWORD(self.geom_index_ops_nd)) else: index_ops = '' else: index_ops = (' ' + style.SQL_KEYWORD(self.geom_index_ops)) output.append((((((((((style.SQL_KEYWORD('CREATE INDEX ') + style.SQL_TABLE(qn(('%s_%s_id' % (db_table, f.column))))) + style.SQL_KEYWORD(' ON ')) + style.SQL_TABLE(qn(db_table))) + style.SQL_KEYWORD(' USING ')) + style.SQL_COLTYPE(self.geom_index_type)) + ' ( ') + style.SQL_FIELD(qn(f.column))) + index_ops) + ' );')) return output
'Returns a dictionary with keys that are the PostgreSQL object identification integers for the PostGIS geometry and/or geography types (if supported).'
def get_postgis_types(self):
cursor = self.connection.cursor() oid_sql = 'SELECT "oid" FROM "pg_type" WHERE "typname" = %s' try: cursor.execute(oid_sql, ('geometry',)) GEOM_TYPE = cursor.fetchone()[0] postgis_types = {GEOM_TYPE: 'GeometryField'} if self.connection.ops.geography: cursor.execute(oid_sql, ('geography',)) GEOG_TYPE = cursor.fetchone()[0] postgis_types[GEOG_TYPE] = ('GeometryField', {'geography': True}) finally: cursor.close() return postgis_types
'The geometry type OID used by PostGIS does not indicate the particular type of field that a geometry column is (e.g., whether it\'s a PointField or a PolygonField). Thus, this routine queries the PostGIS metadata tables to determine the geometry type,'
def get_geometry_type(self, table_name, geo_col):
cursor = self.connection.cursor() try: try: cursor.execute('SELECT "coord_dimension", "srid", "type" FROM "geometry_columns" WHERE "f_table_name"=%s AND "f_geometry_column"=%s', (table_name, geo_col)) row = cursor.fetchone() if (not row): raise GeoIntrospectionError except GeoIntrospectionError: if self.connection.ops.geography: cursor.execute('SELECT "coord_dimension", "srid", "type" FROM "geography_columns" WHERE "f_table_name"=%s AND "f_geography_column"=%s', (table_name, geo_col)) row = cursor.fetchone() if (not row): raise Exception(('Could not find a geometry or geography column for "%s"."%s"' % (table_name, geo_col))) field_type = OGRGeomType(row[2]).django dim = row[0] srid = row[1] field_params = {} if (srid != 4326): field_params['srid'] = srid if (dim != 2): field_params['dim'] = dim finally: cursor.close() return (field_type, field_params)
'Checks if the given aggregate name is supported (that is, if it\'s in `self.valid_aggregates`).'
def check_aggregate_support(self, aggregate):
agg_name = aggregate.__class__.__name__ return (agg_name in self.valid_aggregates)
'Converts geometry WKT returned from a SpatiaLite aggregate.'
def convert_geom(self, wkt, geo_field):
if wkt: return Geometry(wkt, geo_field.srid) else: return None
'Returns None because geometry columnas are added via the `AddGeometryColumn` stored procedure on SpatiaLite.'
def geo_db_type(self, f):
return None
'Returns the distance parameters for the given geometry field, lookup value, and lookup type. SpatiaLite only supports regular cartesian-based queries (no spheroid/sphere calculations for point geometries like PostGIS).'
def get_distance(self, f, value, lookup_type):
if (not value): return [] value = value[0] if isinstance(value, Distance): if f.geodetic(self.connection): raise ValueError('SpatiaLite does not support distance queries on geometry fields with a geodetic coordinate system. Distance objects; use a numeric value of your distance in degrees instead.') else: dist_param = getattr(value, Distance.unit_attname(f.units_name(self.connection))) else: dist_param = value return [dist_param]
'Provides a proper substitution value for Geometries that are not in the SRID of the field. Specifically, this routine will substitute in the Transform() and GeomFromText() function call(s).'
def get_geom_placeholder(self, f, value):
def transform_value(value, srid): return (not ((value is None) or (value.srid == srid))) if hasattr(value, 'expression'): if transform_value(value, f.srid): placeholder = ('%s(%%s, %s)' % (self.transform, f.srid)) else: placeholder = '%s' return (placeholder % self.get_expression_column(value)) elif transform_value(value, f.srid): return ('%s(%s(%%s,%s), %s)' % (self.transform, self.from_text, value.srid, f.srid)) else: return ('%s(%%s,%s)' % (self.from_text, f.srid))
'Helper routine for calling SpatiaLite functions and returning their result.'
def _get_spatialite_func(self, func):
cursor = self.connection._cursor() try: cursor.execute(('SELECT %s' % func)) row = cursor.fetchone() except: raise finally: cursor.close() return row[0]
'Returns the version of GEOS used by SpatiaLite as a string.'
def geos_version(self):
return self._get_spatialite_func('geos_version()')
'Returns the version of the PROJ.4 library used by SpatiaLite.'
def proj4_version(self):
return self._get_spatialite_func('proj4_version()')
'Returns the SpatiaLite library version as a string.'
def spatialite_version(self):
return self._get_spatialite_func('spatialite_version()')
'Returns the SpatiaLite version as a tuple (version string, major, minor, subminor).'
def spatialite_version_tuple(self):
try: version = self.spatialite_version() except DatabaseError: version = None try: tmp = self._get_spatialite_func("X(GeomFromText('POINT(1 1)'))") if (tmp == 1.0): version = '2.3.0' except DatabaseError: pass if (version is None): raise m = self.version_regex.match(version) if m: major = int(m.group('major')) minor1 = int(m.group('minor1')) minor2 = int(m.group('minor2')) else: raise Exception(('Could not parse SpatiaLite version string: %s' % version)) return (version, major, minor1, minor2)
'Returns the spatial aggregate SQL template and function for the given Aggregate instance.'
def spatial_aggregate_sql(self, agg):
agg_name = agg.__class__.__name__ if (not self.check_aggregate_support(agg)): raise NotImplementedError(('%s spatial aggregate is not implmented for this backend.' % agg_name)) agg_name = agg_name.lower() if (agg_name == 'union'): agg_name += 'agg' sql_template = (self.select % '%(function)s(%(field)s)') sql_function = getattr(self, agg_name) return (sql_template, sql_function)
'Returns the SpatiaLite-specific SQL for the given lookup value [a tuple of (alias, column, db_type)], lookup type, lookup value, the model field, and the quoting function.'
def spatial_lookup_sql(self, lvalue, lookup_type, value, field, qn):
(alias, col, db_type) = lvalue geo_col = ('%s.%s' % (qn(alias), qn(col))) if (lookup_type in self.geometry_functions): tmp = self.geometry_functions[lookup_type] if isinstance(tmp, tuple): (op, arg_type) = tmp if (not isinstance(value, (tuple, list))): raise ValueError(('Tuple required for `%s` lookup type.' % lookup_type)) geom = value[0] if (len(value) != 2): raise ValueError(('Incorrect number of parameters given for `%s` lookup type.' % lookup_type)) if (not isinstance(value[1], arg_type)): raise ValueError(('Argument type should be %s, got %s instead.' % (arg_type, type(value[1])))) if (lookup_type == 'relate'): op = op(value[1]) elif (lookup_type in self.distance_functions): op = op[0] else: op = tmp geom = value return op.as_sql(geo_col, self.get_geom_placeholder(field, geom)) elif (lookup_type == 'isnull'): return ('%s IS %sNULL' % (geo_col, (((not value) and 'NOT ') or ''))) raise TypeError(('Got invalid lookup_type: %s' % repr(lookup_type)))
'Returns the name of the metadata column used to store the the feature table name.'
@classmethod def table_name_col(cls):
return 'f_table_name'
'Returns the name of the metadata column used to store the the feature geometry column.'
@classmethod def geom_col_name(cls):
return 'f_geometry_column'
'Creates a test database, prompting the user for confirmation if the database already exists. Returns the name of the test database created. This method is overloaded to load up the SpatiaLite initialization SQL prior to calling the `syncdb` command.'
def create_test_db(self, verbosity=1, autoclobber=False):
from django.core.management import call_command test_database_name = self._get_test_db_name() if (verbosity >= 1): test_db_repr = '' if (verbosity >= 2): test_db_repr = (" ('%s')" % test_database_name) print ("Creating test database for alias '%s'%s..." % (self.connection.alias, test_db_repr)) self._create_test_db(verbosity, autoclobber) self.connection.close() self.connection.settings_dict['NAME'] = test_database_name self.connection.ops.confirm_spatial_components_versions() self.load_spatialite_sql() call_command('syncdb', verbosity=max((verbosity - 1), 0), interactive=False, database=self.connection.alias, load_initial_data=False) call_command('flush', verbosity=max((verbosity - 1), 0), interactive=False, database=self.connection.alias) from django.core.cache import get_cache from django.core.cache.backends.db import BaseDatabaseCache for cache_alias in settings.CACHES: cache = get_cache(cache_alias) if isinstance(cache, BaseDatabaseCache): call_command('createcachetable', cache._table, database=self.connection.alias) cursor = self.connection.cursor() return test_database_name
'Return any spatial index creation SQL for the field.'
def sql_indexes_for_field(self, model, f, style):
from django.contrib.gis.db.models.fields import GeometryField output = super(SpatiaLiteCreation, self).sql_indexes_for_field(model, f, style) if isinstance(f, GeometryField): gqn = self.connection.ops.geo_quote_name qn = self.connection.ops.quote_name db_table = model._meta.db_table output.append(((((((((((((((style.SQL_KEYWORD('SELECT ') + style.SQL_TABLE('AddGeometryColumn')) + '(') + style.SQL_TABLE(gqn(db_table))) + ', ') + style.SQL_FIELD(gqn(f.column))) + ', ') + style.SQL_FIELD(str(f.srid))) + ', ') + style.SQL_COLTYPE(gqn(f.geom_type))) + ', ') + style.SQL_KEYWORD(str(f.dim))) + ', ') + style.SQL_KEYWORD(str(int((not f.null))))) + ');')) if f.spatial_index: output.append(((((((style.SQL_KEYWORD('SELECT ') + style.SQL_TABLE('CreateSpatialIndex')) + '(') + style.SQL_TABLE(gqn(db_table))) + ', ') + style.SQL_FIELD(gqn(f.column))) + ');')) return output
'This routine loads up the SpatiaLite SQL file.'
def load_spatialite_sql(self):
if (self.connection.ops.spatial_version[:2] >= (2, 4)): cur = self.connection._cursor() cur.execute('SELECT InitSpatialMetaData()') else: spatialite_sql = self.spatialite_init_file() if (not os.path.isfile(spatialite_sql)): raise ImproperlyConfigured(('Could not find the required SpatiaLite initialization SQL file (necessary for testing): %s' % spatialite_sql)) with open(spatialite_sql, 'r') as sql_fh: cur = self.connection._cursor() cur.executescript(sql_fh.read())
'The placeholder here has to include MySQL\'s WKT constructor. Because MySQL does not support spatial transformations, there is no need to modify the placeholder based on the contents of the given value.'
def get_geom_placeholder(self, value, srid):
if hasattr(value, 'expression'): placeholder = self.get_expression_column(value) else: placeholder = ('%s(%%s)' % self.from_text) return placeholder
'Integrate the cases handled both by the base GeoSQLCompiler and the main MySQL compiler (converting 0/1 to True/False for boolean fields). Refs #15169.'
def resolve_columns(self, row, fields=()):
row = BaseGeoSQLCompiler.resolve_columns(self, row, fields) return SQLCompiler.resolve_columns(self, row, fields)
'Test initialization of distance models.'
def test01_init(self):
self.assertEqual(9, SouthTexasCity.objects.count()) self.assertEqual(9, SouthTexasCityFt.objects.count()) self.assertEqual(11, AustraliaCity.objects.count()) self.assertEqual(4, SouthTexasZipcode.objects.count()) self.assertEqual(4, CensusZipcode.objects.count()) self.assertEqual(1, Interstate.objects.count()) self.assertEqual(1, SouthTexasInterstate.objects.count())
'Testing the `dwithin` lookup type.'
@no_spatialite def test02_dwithin(self):
tx_dists = [(7000, 22965.83), D(km=7), D(mi=4.349)] au_dists = [(0.5, 32000), D(km=32), D(mi=19.884)] tx_cities = ['Downtown Houston', 'Southside Place'] au_cities = ['Mittagong', 'Shellharbour', 'Thirroul', 'Wollongong'] for dist in tx_dists: if isinstance(dist, tuple): (dist1, dist2) = dist else: dist1 = dist2 = dist qs1 = SouthTexasCity.objects.filter(point__dwithin=(self.stx_pnt, dist1)) qs2 = SouthTexasCityFt.objects.filter(point__dwithin=(self.stx_pnt, dist2)) for qs in (qs1, qs2): self.assertEqual(tx_cities, self.get_names(qs)) for dist in au_dists: if (isinstance(dist, D) and (not oracle)): type_error = True else: type_error = False if isinstance(dist, tuple): if oracle: dist = dist[1] else: dist = dist[0] qs = AustraliaCity.objects.order_by('name') if type_error: self.assertRaises(ValueError, AustraliaCity.objects.filter(point__dwithin=(self.au_pnt, dist)).count) else: self.assertEqual(au_cities, self.get_names(qs.filter(point__dwithin=(self.au_pnt, dist))))
'Testing the `distance` GeoQuerySet method on projected coordinate systems.'
def test03a_distance_method(self):
lagrange = GEOSGeometry('POINT(-96.876369 29.905320)', 4326) m_distances = [147075.069813, 139630.198056, 140888.552826, 138809.684197, 158309.246259, 212183.594374, 70870.188967, 165337.758878, 139196.085105] ft_distances = [482528.79154625, 458103.408123001, 462231.860397575, 455411.438904354, 519386.252102563, 696139.009211594, 232513.278304279, 542445.630586414, 456679.155883207] dist1 = SouthTexasCity.objects.distance(lagrange, field_name='point') dist2 = SouthTexasCity.objects.distance(lagrange) if (spatialite or oracle): dist_qs = [dist1, dist2] else: dist3 = SouthTexasCityFt.objects.distance(lagrange.ewkt) dist4 = SouthTexasCityFt.objects.distance(lagrange) dist_qs = [dist1, dist2, dist3, dist4] if oracle: tol = 2 else: tol = 5 for qs in dist_qs: for (i, c) in enumerate(qs): self.assertAlmostEqual(m_distances[i], c.distance.m, tol) self.assertAlmostEqual(ft_distances[i], c.distance.survey_ft, tol)
'Testing the `distance` GeoQuerySet method on geodetic coordnate systems.'
@no_spatialite def test03b_distance_method(self):
if oracle: tol = 2 else: tol = 5 ls = LineString(((150.902, (-34.4245)), (150.87, (-34.5789)))) if (oracle or connection.ops.geography): distances = [1120954.92533513, 140575.720018241, 640396.662906304, 60580.9693849269, 972807.955955075, 568451.8357838, 40435.4335201384, 0, 68272.3896586844, 12375.0643697706, 0] qs = AustraliaCity.objects.distance(ls).order_by('name') for (city, distance) in zip(qs, distances): self.assertAlmostEqual(distance, city.distance.m, 0) else: self.assertRaises(ValueError, AustraliaCity.objects.distance, ls) self.assertRaises(ValueError, AustraliaCity.objects.distance, ls.wkt) if (connection.ops.postgis and (connection.ops.proj_version_tuple() >= (4, 7, 0))): spheroid_distances = [60504.0628957201, 77023.9489850262, 49154.8867574404, 90847.4358768573, 217402.811919332, 709599.234564757, 640011.483550888, 7772.00667991925, 1047861.78619339, 1165126.55236034] sphere_distances = [60580.9693849267, 77144.0435286473, 49199.4415344719, 90804.7533823494, 217713.384600405, 709134.127242793, 639828.157159169, 7786.82949717788, 1049204.06569028, 1162623.7238134] else: spheroid_distances = [60504.0628825298, 77023.948962654, 49154.8867507115, 90847.435881812, 217402.811862568, 709599.234619957, 640011.483583758, 7772.00667666425, 1047861.7859506, 1165126.55237647] sphere_distances = [60580.7612632291, 77143.7785056615, 49199.2725132184, 90804.4414289463, 217712.63666124, 709131.691061906, 639825.959074112, 7786.80274606706, 1049200.46122281, 1162619.7297006] hillsdale = AustraliaCity.objects.get(name='Hillsdale') qs = AustraliaCity.objects.exclude(id=hillsdale.id).distance(hillsdale.point, spheroid=True) for (i, c) in enumerate(qs): self.assertAlmostEqual(spheroid_distances[i], c.distance.m, tol) if postgis: qs = AustraliaCity.objects.exclude(id=hillsdale.id).distance(hillsdale.point) for (i, c) in enumerate(qs): self.assertAlmostEqual(sphere_distances[i], c.distance.m, tol)
'Testing the `distance` GeoQuerySet method used with `transform` on a geographic field.'
@no_oracle def test03c_distance_method(self):
if (not connection.ops.geography): self.assertRaises(ValueError, CensusZipcode.objects.distance, self.stx_pnt) z = SouthTexasZipcode.objects.get(name='77005') dists_m = [3553.30384972258, 1243.18391525602, 2186.15439472242] buf1 = z.poly.centroid.buffer(100) buf2 = buf1.transform(4269, clone=True) ref_zips = ['77002', '77025', '77401'] for buf in [buf1, buf2]: qs = CensusZipcode.objects.exclude(name='77005').transform(32140).distance(buf) self.assertEqual(ref_zips, self.get_names(qs)) for (i, z) in enumerate(qs): self.assertAlmostEqual(z.distance.m, dists_m[i], 5)
'Testing the `distance_lt`, `distance_gt`, `distance_lte`, and `distance_gte` lookup types.'
def test04_distance_lookups(self):
qs1 = SouthTexasCity.objects.filter(point__distance_gte=(self.stx_pnt, D(km=7))).filter(point__distance_lte=(self.stx_pnt, D(km=20))) if (spatialite or oracle): dist_qs = (qs1,) else: qs2 = SouthTexasCityFt.objects.filter(point__distance_gte=(self.stx_pnt, D(km=7))).filter(point__distance_lte=(self.stx_pnt, D(km=20))) dist_qs = (qs1, qs2) for qs in dist_qs: cities = self.get_names(qs) self.assertEqual(cities, ['Bellaire', 'Pearland', 'West University Place']) z = SouthTexasZipcode.objects.get(name='77005') qs = SouthTexasZipcode.objects.exclude(name='77005').filter(poly__distance_lte=(z.poly, D(m=275))) self.assertEqual(['77025', '77401'], self.get_names(qs)) qs = SouthTexasZipcode.objects.exclude(name='77005').filter(poly__distance_lte=(z.poly, D(m=300))) self.assertEqual(['77002', '77025', '77401'], self.get_names(qs))
'Testing distance lookups on geodetic coordinate systems.'
def test05_geodetic_distance_lookups(self):
line = GEOSGeometry('LINESTRING(144.9630 -37.8143,151.2607 -33.8870)', 4326) dist_qs = AustraliaCity.objects.filter(point__distance_lte=(line, D(km=100))) if (oracle or connection.ops.geography): self.assertEqual(9, dist_qs.count()) self.assertEqual(['Batemans Bay', 'Canberra', 'Hillsdale', 'Melbourne', 'Mittagong', 'Shellharbour', 'Sydney', 'Thirroul', 'Wollongong'], self.get_names(dist_qs)) else: self.assertRaises(ValueError, dist_qs.count) if spatialite: return self.assertRaises(ValueError, len, AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)', D(km=100), 'spheroid', '4'))) self.assertRaises(ValueError, len, AustraliaCity.objects.filter(point__distance_lte=('POINT(5 23)',))) hobart = AustraliaCity.objects.get(name='Hobart') qs = AustraliaCity.objects.exclude(name='Hobart').filter(point__distance_lte=(hobart.point, D(mi=550))) cities = self.get_names(qs) self.assertEqual(cities, ['Batemans Bay', 'Canberra', 'Melbourne']) wollongong = AustraliaCity.objects.get(name='Wollongong') (d1, d2) = (D(yd=19500), D(nm=400)) gq1 = Q(point__distance_lte=(wollongong.point, d1)) gq2 = Q(point__distance_gte=(wollongong.point, d2)) qs1 = AustraliaCity.objects.exclude(name='Wollongong').filter((gq1 | gq2)) if postgis: gq3 = Q(point__distance_lte=(wollongong.point, d1, 'spheroid')) gq4 = Q(point__distance_gte=(wollongong.point, d2, 'spheroid')) qs2 = AustraliaCity.objects.exclude(name='Wollongong').filter((gq3 | gq4)) querysets = [qs1, qs2] else: querysets = [qs1] for qs in querysets: cities = self.get_names(qs) self.assertEqual(cities, ['Adelaide', 'Hobart', 'Shellharbour', 'Thirroul'])
'Testing the `area` GeoQuerySet method.'
def test06_area(self):
area_sq_m = [5437908.90234375, 10183031.4389648, 11254471.0073242, 9881708.91772461] tol = 2 for (i, z) in enumerate(SouthTexasZipcode.objects.area()): self.assertAlmostEqual(area_sq_m[i], z.area.sq_m, tol)
'Testing the `length` GeoQuerySet method.'
def test07_length(self):
len_m1 = 473504.769553813 len_m2 = 4617.668 if spatialite: self.assertRaises(ValueError, Interstate.objects.length) else: qs = Interstate.objects.length() if oracle: tol = 2 else: tol = 3 self.assertAlmostEqual(len_m1, qs[0].length.m, tol) i10 = SouthTexasInterstate.objects.length().get(name='I-10') self.assertAlmostEqual(len_m2, i10.length.m, 2)
'Testing the `perimeter` GeoQuerySet method.'
@no_spatialite def test08_perimeter(self):
perim_m = [18404.3550889361, 15627.2108551001, 20632.5588368978, 17094.5996143697] if oracle: tol = 2 else: tol = 7 for (i, z) in enumerate(SouthTexasZipcode.objects.perimeter()): self.assertAlmostEqual(perim_m[i], z.perimeter.m, tol) for (i, c) in enumerate(SouthTexasCity.objects.perimeter(model_att='perim')): self.assertEqual(0, c.perim.m)
'Testing the measurement GeoQuerySet methods on fields with NULL values.'
def test09_measurement_null_fields(self):
SouthTexasZipcode.objects.create(name='78212') htown = SouthTexasCity.objects.get(name='Downtown Houston') z = SouthTexasZipcode.objects.distance(htown.point).area().get(name='78212') self.assertEqual(None, z.distance) self.assertEqual(None, z.area)
'Make sure data is 3D and has expected Z values -- shouldn\'t change because of coordinate system.'
def test_3d_hasz(self):
self._load_interstate_data() for (name, line, exp_z) in interstate_data: interstate = Interstate3D.objects.get(name=name) interstate_proj = InterstateProj3D.objects.get(name=name) for i in [interstate, interstate_proj]: self.assertTrue(i.line.hasz) self.assertEqual(exp_z, tuple(i.line.z)) self._load_city_data() for (name, pnt_data) in city_data: city = City3D.objects.get(name=name) z = pnt_data[2] self.assertTrue(city.point.hasz) self.assertEqual(z, city.point.z)
'Test the creation of polygon 3D models.'
def test_3d_polygons(self):
self._load_polygon_data() p3d = Polygon3D.objects.get(name=u'3D BBox') self.assertTrue(p3d.poly.hasz) self.assertIsInstance(p3d.poly, Polygon) self.assertEqual(p3d.poly.srid, 32140)
'Testing LayerMapping on 3D models.'
def test_3d_layermapping(self):
point_mapping = {u'point': u'POINT'} mpoint_mapping = {u'mpoint': u'MULTIPOINT'} lm = LayerMapping(Point2D, vrt_file, point_mapping, transform=False) lm.save() self.assertEqual(3, Point2D.objects.count()) self.assertRaises(LayerMapError, LayerMapping, Point3D, city_file, point_mapping, transform=False) lm = LayerMapping(Point3D, vrt_file, point_mapping, transform=False) lm.save() self.assertEqual(3, Point3D.objects.count()) lm = LayerMapping(MultiPoint3D, vrt_file, mpoint_mapping, transform=False) lm.save() self.assertEqual(3, MultiPoint3D.objects.count())
'Test GeoQuerySet.kml() with Z values.'
def test_kml(self):
self._load_city_data() h = City3D.objects.kml(precision=6).get(name=u'Houston') ref_kml_regex = re.compile(u'^<Point><coordinates>-95.363\\d+,29.763\\d+,18</coordinates></Point>$') self.assertTrue(ref_kml_regex.match(h.kml))
'Test GeoQuerySet.geojson() with Z values.'
def test_geojson(self):
self._load_city_data() h = City3D.objects.geojson(precision=6).get(name=u'Houston') ref_json_regex = re.compile(u'^{"type":"Point","coordinates":\\[-95.363151,29.763374,18(\\.0+)?\\]}$') self.assertTrue(ref_json_regex.match(h.geojson))
'Testing the Union aggregate of 3D models.'
def test_union(self):
self._load_city_data() ref_ewkt = u'SRID=4326;MULTIPOINT(-123.305196 48.462611 15,-104.609252 38.255001 1433,-97.521157 34.464642 380,-96.801611 32.782057 147,-95.363151 29.763374 18,-95.23506 38.971823 251,-87.650175 41.850385 181,174.783117 -41.315268 14)' ref_union = GEOSGeometry(ref_ewkt) union = City3D.objects.aggregate(Union(u'point'))[u'point__union'] self.assertTrue(union.hasz) self.assertEqual(ref_union, union)
'Testing the Extent3D aggregate for 3D models.'
def test_extent(self):
self._load_city_data() ref_extent3d = ((-123.305196), (-41.315268), 14, 174.783117, 48.462611, 1433) extent1 = City3D.objects.aggregate(Extent3D(u'point'))[u'point__extent3d'] extent2 = City3D.objects.extent3d() def check_extent3d(extent3d, tol=6): for (ref_val, ext_val) in zip(ref_extent3d, extent3d): self.assertAlmostEqual(ref_val, ext_val, tol) for e3d in [extent1, extent2]: check_extent3d(e3d)
'Testing GeoQuerySet.perimeter() on 3D fields.'
def test_perimeter(self):
self._load_polygon_data() ref_perim_3d = 76859.2620451 ref_perim_2d = 76859.2577803 tol = 6 self.assertAlmostEqual(ref_perim_2d, Polygon2D.objects.perimeter().get(name=u'2D BBox').perimeter.m, tol) self.assertAlmostEqual(ref_perim_3d, Polygon3D.objects.perimeter().get(name=u'3D BBox').perimeter.m, tol)
'Testing GeoQuerySet.length() on 3D fields.'
def test_length(self):
self._load_interstate_data() tol = 3 ref_length_2d = 4368.1721949481 ref_length_3d = 4368.62547052088 self.assertAlmostEqual(ref_length_2d, Interstate2D.objects.length().get(name=u'I-45').length.m, tol) self.assertAlmostEqual(ref_length_3d, Interstate3D.objects.length().get(name=u'I-45').length.m, tol) ref_length_2d = 4367.71564892392 ref_length_3d = 4368.16897234101 self.assertAlmostEqual(ref_length_2d, InterstateProj2D.objects.length().get(name=u'I-45').length.m, tol) self.assertAlmostEqual(ref_length_3d, InterstateProj3D.objects.length().get(name=u'I-45').length.m, tol)
'Testing GeoQuerySet.scale() on Z values.'
def test_scale(self):
self._load_city_data() zscales = ((-3), 4, 23) for zscale in zscales: for city in City3D.objects.scale(1.0, 1.0, zscale): self.assertEqual((city_dict[city.name][2] * zscale), city.scale.z)
'Testing GeoQuerySet.translate() on Z values.'
def test_translate(self):
self._load_city_data() ztranslations = (5.23, 23, (-17)) for ztrans in ztranslations: for city in City3D.objects.translate(0, 0, ztrans): self.assertEqual((city_dict[city.name][2] + ztrans), city.translate.z)
'Ensure geography features loaded properly.'
def test01_fixture_load(self):
self.assertEqual(8, City.objects.count())
'Testing GeoQuerySet distance lookup support on non-point geography fields.'
def test02_distance_lookup(self):
z = Zipcode.objects.get(code='77002') cities1 = list(City.objects.filter(point__distance_lte=(z.poly, D(mi=500))).order_by('name').values_list('name', flat=True)) cities2 = list(City.objects.filter(point__dwithin=(z.poly, D(mi=500))).order_by('name').values_list('name', flat=True)) for cities in [cities1, cities2]: self.assertEqual(['Dallas', 'Houston', 'Oklahoma City'], cities)
'Testing GeoQuerySet.distance() support on non-point geography fields.'
def test03_distance_method(self):
htown = City.objects.get(name='Houston') qs = Zipcode.objects.distance(htown.point)