desc
stringlengths
3
26.7k
decl
stringlengths
11
7.89k
bodies
stringlengths
8
553k
'Determine whether a given comment on a given object should be allowed to show up immediately, or should be marked non-public and await approval. Return ``True`` if the comment should be moderated (marked non-public), ``False`` otherwise.'
def moderate(self, comment, content_object, request):
if (self.auto_moderate_field and (self.moderate_after is not None)): moderate_after_date = getattr(content_object, self.auto_moderate_field) if ((moderate_after_date is not None) and (self._get_delta(timezone.now(), moderate_after_date).days >= self.moderate_after)): return True return False
'Send email notification of a new comment to site staff when email notifications have been requested.'
def email(self, comment, content_object, request):
if (not self.email_notification): return recipient_list = [manager_tuple[1] for manager_tuple in settings.MANAGERS] t = loader.get_template('comments/comment_notification_email.txt') c = Context({'comment': comment, 'content_object': content_object}) subject = ('[%s] New comment posted on "%s"' % (get_current_site(request).name, content_object)) message = t.render(c) send_mail(subject, message, settings.DEFAULT_FROM_EMAIL, recipient_list, fail_silently=True)
'Hook up the moderation methods to pre- and post-save signals from the comment models.'
def connect(self):
signals.comment_will_be_posted.connect(self.pre_save_moderation, sender=comments.get_model()) signals.comment_was_posted.connect(self.post_save_moderation, sender=comments.get_model())
'Register a model or a list of models for comment moderation, using a particular moderation class. Raise ``AlreadyModerated`` if any of the models are already registered.'
def register(self, model_or_iterable, moderation_class):
if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if (model in self._registry): raise AlreadyModerated(("The model '%s' is already being moderated" % model._meta.module_name)) self._registry[model] = moderation_class(model)
'Remove a model or a list of models from the list of models whose comments will be moderated. Raise ``NotModerated`` if any of the models are not currently registered for moderation.'
def unregister(self, model_or_iterable):
if isinstance(model_or_iterable, ModelBase): model_or_iterable = [model_or_iterable] for model in model_or_iterable: if (model not in self._registry): raise NotModerated(("The model '%s' is not currently being moderated" % model._meta.module_name)) del self._registry[model]
'Apply any necessary pre-save moderation steps to new comments.'
def pre_save_moderation(self, sender, comment, request, **kwargs):
model = comment.content_type.model_class() if (model not in self._registry): return content_object = comment.content_object moderation_class = self._registry[model] if (not moderation_class.allow(comment, content_object, request)): return False if moderation_class.moderate(comment, content_object, request): comment.is_public = False
'Apply any necessary post-save moderation steps to new comments.'
def post_save_moderation(self, sender, comment, request, **kwargs):
model = comment.content_type.model_class() if (model not in self._registry): return self._registry[model].email(comment, comment.content_object, request)
'When the redirect target is \'\', return a 410'
def test_response_gone(self):
Redirect.objects.create(site=self.site, old_path='/initial', new_path='') response = self.client.get('/initial') self.assertEqual(response.status_code, 410)
'Returns the ModelDatabrowse class for this model.'
def model_databrowse(self):
return self.site.registry[self.model]
'Generator that yields EasyInstanceFields for each field in this EasyInstance\'s model.'
def fields(self):
for f in (self.model.model._meta.fields + self.model.model._meta.many_to_many): (yield EasyInstanceField(self.model, self, f))
'Generator that yields dictionaries of all models that have this EasyInstance\'s model as a ForeignKey or ManyToManyField, along with lists of related objects.'
def related_objects(self):
for rel_object in (self.model.model._meta.get_all_related_objects() + self.model.model._meta.get_all_related_many_to_many_objects()): if (rel_object.model not in self.model.model_list): continue em = EasyModel(self.model.site, rel_object.model) (yield {u'model': em, u'related_field': rel_object.field.verbose_name, u'object_list': [EasyInstance(em, i) for i in getattr(self.instance, rel_object.get_accessor_name()).all()]})
'Returns a list of values for this field for this instance. It\'s a list so we can accomodate many-to-many fields.'
def values(self):
if self.field.rel: if isinstance(self.field.rel, models.ManyToOneRel): objs = getattr(self.instance.instance, self.field.name) elif isinstance(self.field.rel, models.ManyToManyRel): return list(getattr(self.instance.instance, self.field.name).all()) elif self.field.choices: objs = dict(self.field.choices).get(self.raw_value, EMPTY_VALUE) elif (isinstance(self.field, models.DateField) or isinstance(self.field, models.TimeField)): if self.raw_value: if isinstance(self.field, models.DateTimeField): objs = capfirst(formats.date_format(self.raw_value, u'DATETIME_FORMAT')) elif isinstance(self.field, models.TimeField): objs = capfirst(formats.time_format(self.raw_value, u'TIME_FORMAT')) else: objs = capfirst(formats.date_format(self.raw_value, u'DATE_FORMAT')) else: objs = EMPTY_VALUE elif (isinstance(self.field, models.BooleanField) or isinstance(self.field, models.NullBooleanField)): objs = {True: u'Yes', False: u'No', None: u'Unknown'}[self.raw_value] else: objs = self.raw_value return [objs]
'Returns a list of (value, URL) tuples.'
def urls(self):
plugin_urls = [] for (plugin_name, plugin) in self.model.model_databrowse().plugins.items(): urls = plugin.urls(plugin_name, self) if (urls is not None): return zip(self.values(), urls) if self.field.rel: m = EasyModel(self.model.site, self.field.rel.to) if (self.field.rel.to in self.model.model_list): lst = [] for value in self.values(): if (value is None): continue url = (u'%s%s/%s/objects/%s/' % (self.model.site.root_url, m.model._meta.app_label, m.model._meta.module_name, iri_to_uri(value._get_pk_val()))) lst.append((smart_text(value), url)) else: lst = [(value, None) for value in self.values()] elif self.field.choices: lst = [] for value in self.values(): url = (u'%s%s/%s/fields/%s/%s/' % (self.model.site.root_url, self.model.model._meta.app_label, self.model.model._meta.module_name, self.field.name, iri_to_uri(self.raw_value))) lst.append((value, url)) elif isinstance(self.field, models.URLField): val = list(self.values())[0] lst = [(val, iri_to_uri(val))] else: lst = [(list(self.values())[0], None)] return lst
'Given an EasyInstanceField object, returns a list of URLs for this plugin\'s views of this object. These URLs should be absolute. Returns None if the EasyInstanceField object doesn\'t get a list of plugin-specific URLs.'
def urls(self, plugin_name, easy_instance_field):
return None
'Returns a snippet of HTML to include on the model index page.'
def model_index_html(self, request, model, site):
return u''
'Handles main URL routing for a plugin\'s model-specific pages.'
def model_view(self, request, model_databrowse, url):
raise NotImplementedError
'Handles main URL routing for the databrowse app. `url` is the remainder of the URL -- e.g. \'objects/3\'.'
def root(self, request, url):
if (url is None): return self.main_view(request) try: (plugin_name, rest_of_url) = url.split(u'/', 1) except ValueError: (plugin_name, rest_of_url) = (url, None) try: plugin = self.plugins[plugin_name] except KeyError: raise http.Http404(u'A plugin with the requested name does not exist.') return plugin.model_view(request, self, rest_of_url)
'Registers the given model(s) with the given databrowse site. The model(s) should be Model classes, not instances. If a databrowse class isn\'t given, it will use DefaultModelDatabrowse (the default databrowse options). If a model is already registered, this will raise AlreadyRegistered.'
def register(self, *model_list, **options):
databrowse_class = options.pop(u'databrowse_class', DefaultModelDatabrowse) for model in model_list: if (model in self.registry): raise AlreadyRegistered((u'The model %s is already registered' % model.__name__)) self.registry[model] = databrowse_class
'Unregisters the given model(s). If a model isn\'t already registered, this will raise NotRegistered.'
def unregister(self, *model_list):
for model in model_list: if (model not in self.registry): raise NotRegistered((u'The model %s is not registered' % model.__name__)) del self.registry[model]
'Handles main URL routing for the databrowse app. `url` is the remainder of the URL -- e.g. \'comments/comment/\'.'
def root(self, request, url):
self.root_url = request.path[:(len(request.path) - len(url))] url = url.rstrip(u'/') if (url == u''): return self.index(request) elif (u'/' in url): return self.model_page(request, *url.split(u'/', 2)) raise http.Http404(u'The requested databrowse page does not exist.')
'Handles the model-specific functionality of the databrowse site, delegating to the appropriate ModelDatabrowse class.'
def model_page(self, request, app_label, model_name, rest_of_url=None):
model = models.get_model(app_label, model_name) if (model is None): raise http.Http404((u'App %r, model %r, not found.' % (app_label, model_name))) try: databrowse_class = self.registry[model] except KeyError: raise http.Http404(u'This model exists but has not been registered with databrowse.') return databrowse_class(model, self).root(request, rest_of_url)
'Helper function that returns a dictionary of all DateFields or DateTimeFields in the given model. If self.field_names is set, it takes take that into account when building the dictionary.'
def field_dict(self, model):
if (self.field_names is None): return dict([(f.name, f) for f in model._meta.fields if isinstance(f, models.DateField)]) else: return dict([(f.name, f) for f in model._meta.fields if (isinstance(f, models.DateField) and (f.name in self.field_names))])
'Helper function that returns a dictionary of all fields in the given model. If self.field_filter is set, it only includes the fields that match the filter.'
def field_dict(self, model):
if self.field_filter: return dict([(f.name, f) for f in model._meta.fields if self.field_filter(f)]) else: return dict([(f.name, f) for f in model._meta.fields if ((not f.rel) and (not f.primary_key) and (not f.unique) and (not isinstance(f, (models.AutoField, models.TextField))))])
'Initializes the GeoIP object, no parameters are required to use default settings. Keyword arguments may be passed in to customize the locations of the GeoIP data sets. * path: Base directory to where GeoIP data is located or the full path to where the city or country data files (*.dat) are located. Assumes that both the city and country data sets are located in this directory; overrides the GEOIP_PATH settings attribute. * cache: The cache settings when opening up the GeoIP datasets, and may be an integer in (0, 1, 2, 4, 8) corresponding to the GEOIP_STANDARD, GEOIP_MEMORY_CACHE, GEOIP_CHECK_CACHE, GEOIP_INDEX_CACHE, and GEOIP_MMAP_CACHE, `GeoIPOptions` C API settings, respectively. Defaults to 0, meaning that the data is read from the disk. * country: The name of the GeoIP country data file. Defaults to \'GeoIP.dat\'; overrides the GEOIP_COUNTRY settings attribute. * city: The name of the GeoIP city data file. Defaults to \'GeoLiteCity.dat\'; overrides the GEOIP_CITY settings attribute.'
def __init__(self, path=None, cache=0, country=None, city=None):
if (cache in self.cache_options): self._cache = cache else: raise GeoIPException(('Invalid GeoIP caching option: %s' % cache)) if (not path): path = GEOIP_SETTINGS.get('GEOIP_PATH', None) if (not path): raise GeoIPException('GeoIP path must be provided via parameter or the GEOIP_PATH setting.') if (not isinstance(path, six.string_types)): raise TypeError(('Invalid path type: %s' % type(path).__name__)) if os.path.isdir(path): country_db = os.path.join(path, (country or GEOIP_SETTINGS.get('GEOIP_COUNTRY', 'GeoIP.dat'))) if os.path.isfile(country_db): self._country = GeoIP_open(country_db, cache) self._country_file = country_db city_db = os.path.join(path, (city or GEOIP_SETTINGS.get('GEOIP_CITY', 'GeoLiteCity.dat'))) if os.path.isfile(city_db): self._city = GeoIP_open(city_db, cache) self._city_file = city_db elif os.path.isfile(path): ptr = GeoIP_open(path, cache) info = GeoIP_database_info(ptr) if lite_regex.match(info): self._city = ptr self._city_file = path elif free_regex.match(info): self._country = ptr self._country_file = path else: raise GeoIPException(('Unable to recognize database edition: %s' % info)) else: raise GeoIPException('GeoIP path must be a valid file or directory.')
'Helper routine for checking the query and database availability.'
def _check_query(self, query, country=False, city=False, city_or_country=False):
if (not isinstance(query, six.string_types)): raise TypeError(('GeoIP query must be a string, not type %s' % type(query).__name__)) query = query.encode('ascii') if (city_or_country and (not (self._country or self._city))): raise GeoIPException('Invalid GeoIP country and city data files.') elif (country and (not self._country)): raise GeoIPException(('Invalid GeoIP country data file: %s' % self._country_file)) elif (city and (not self._city)): raise GeoIPException(('Invalid GeoIP city data file: %s' % self._city_file)) return query
'Returns a dictionary of city information for the given IP address or Fully Qualified Domain Name (FQDN). Some information in the dictionary may be undefined (None).'
def city(self, query):
query = self._check_query(query, city=True) if ipv4_re.match(query): return GeoIP_record_by_addr(self._city, c_char_p(query)) else: return GeoIP_record_by_name(self._city, c_char_p(query))
'Returns the country code for the given IP Address or FQDN.'
def country_code(self, query):
query = self._check_query(query, city_or_country=True) if self._country: if ipv4_re.match(query): return GeoIP_country_code_by_addr(self._country, query) else: return GeoIP_country_code_by_name(self._country, query) else: return self.city(query)['country_code']
'Returns the country name for the given IP Address or FQDN.'
def country_name(self, query):
query = self._check_query(query, city_or_country=True) if self._country: if ipv4_re.match(query): return GeoIP_country_name_by_addr(self._country, query) else: return GeoIP_country_name_by_name(self._country, query) else: return self.city(query)['country_name']
'Returns a dictonary with with the country code and name when given an IP address or a Fully Qualified Domain Name (FQDN). For example, both \'24.124.1.80\' and \'djangoproject.com\' are valid parameters.'
def country(self, query):
return {'country_code': self.country_code(query), 'country_name': self.country_name(query)}
'Returns a tuple of the (longitude, latitude) for the given query.'
def lon_lat(self, query):
return self.coords(query)
'Returns a tuple of the (latitude, longitude) for the given query.'
def lat_lon(self, query):
return self.coords(query, ('latitude', 'longitude'))
'Returns a GEOS Point object for the given query.'
def geos(self, query):
ll = self.lon_lat(query) if ll: from django.contrib.gis.geos import Point return Point(ll, srid=4326) else: return None
'Returns information about the GeoIP country database.'
@property def country_info(self):
if (self._country is None): ci = ('No GeoIP Country data in "%s"' % self._country_file) else: ci = GeoIP_database_info(self._country) return ci
'Retuns information about the GeoIP city database.'
@property def city_info(self):
if (self._city is None): ci = ('No GeoIP City data in "%s"' % self._city_file) else: ci = GeoIP_database_info(self._city) return ci
'Returns information about the GeoIP library and databases in use.'
@property def info(self):
info = '' if GeoIP_lib_version: info += ('GeoIP Library:\n DCTB %s\n' % GeoIP_lib_version()) return (info + ('Country:\n DCTB %s\nCity:\n DCTB %s' % (self.country_info, self.city_info)))
'Testing GeoIP initialization.'
def test01_init(self):
g1 = GeoIP() path = settings.GEOIP_PATH g2 = GeoIP(path, 0) g3 = GeoIP.open(path, 0) for g in (g1, g2, g3): self.assertEqual(True, bool(g._country)) self.assertEqual(True, bool(g._city)) city = os.path.join(path, u'GeoLiteCity.dat') cntry = os.path.join(path, u'GeoIP.dat') g4 = GeoIP(city, country=u'') self.assertEqual(None, g4._country) g5 = GeoIP(cntry, city=u'') self.assertEqual(None, g5._city) bad_params = (23, u'foo', 15.23) for bad in bad_params: self.assertRaises(GeoIPException, GeoIP, cache=bad) if isinstance(bad, six.string_types): e = GeoIPException else: e = TypeError self.assertRaises(e, GeoIP, bad, 0)
'Testing GeoIP query parameter checking.'
def test02_bad_query(self):
cntry_g = GeoIP(city=u'<foo>') self.assertRaises(GeoIPException, cntry_g.city, u'google.com') self.assertRaises(GeoIPException, cntry_g.coords, u'yahoo.com') self.assertRaises(TypeError, cntry_g.country_code, 17) self.assertRaises(TypeError, cntry_g.country_name, GeoIP)
'Testing GeoIP country querying methods.'
def test03_country(self):
g = GeoIP(city=u'<foo>') fqdn = u'www.google.com' addr = u'12.215.42.19' for query in (fqdn, addr): for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name): self.assertEqual(u'US', func(query)) for func in (g.country_name, g.country_name_by_addr, g.country_name_by_name): self.assertEqual(u'United States', func(query)) self.assertEqual({u'country_code': u'US', u'country_name': u'United States'}, g.country(query))
'Testing GeoIP city querying methods.'
def test04_city(self):
g = GeoIP(country=u'<foo>') addr = u'128.249.1.1' fqdn = u'tmc.edu' for query in (fqdn, addr): for func in (g.country_code, g.country_code_by_addr, g.country_code_by_name): self.assertEqual(u'US', func(query)) for func in (g.country_name, g.country_name_by_addr, g.country_name_by_name): self.assertEqual(u'United States', func(query)) self.assertEqual({u'country_code': u'US', u'country_name': u'United States'}, g.country(query)) d = g.city(query) self.assertEqual(u'USA', d[u'country_code3']) self.assertEqual(u'Houston', d[u'city']) self.assertEqual(u'TX', d[u'region']) self.assertEqual(713, d[u'area_code']) geom = g.geos(query) self.assertTrue(isinstance(geom, GEOSGeometry)) (lon, lat) = ((-95.401), 29.7079) lat_lon = g.lat_lon(query) lat_lon = (lat_lon[1], lat_lon[0]) for tup in (geom.tuple, g.coords(query), g.lon_lat(query), lat_lon): self.assertAlmostEqual(lon, tup[0], 4) self.assertAlmostEqual(lat, tup[1], 4)
'Testing that GeoIP strings are properly encoded, see #16553.'
def test05_unicode_response(self):
g = GeoIP() d = g.city(u'62.224.93.23') self.assertEqual(u'Sch\xfcmberg', d[u'city'])
'Testing that GeoIP accepts unicode string queries, see #17059.'
def test06_unicode_query(self):
g = GeoIP() d = g.country(u'whitehouse.gov') self.assertEqual(u'US', d[u'country_code'])
'Proxy initializes on the given Geometry class (not an instance) and the GeometryField.'
def __init__(self, klass, field):
self._field = field self._klass = klass
'This accessor retrieves the geometry, initializing it using the geometry class specified during initialization and the HEXEWKB value of the field. Currently, only GEOS or OGR geometries are supported.'
def __get__(self, obj, type=None):
if (obj is None): return self geom_value = obj.__dict__[self._field.attname] if isinstance(geom_value, self._klass): geom = geom_value elif ((geom_value is None) or (geom_value == '')): geom = None else: geom = self._klass(geom_value) setattr(obj, self._field.attname, geom) return geom
'This accessor sets the proxied geometry with the geometry class specified during initialization. Values of None, HEXEWKB, or WKT may be used to set the geometry as well.'
def __set__(self, obj, value):
gtype = self._field.geom_type if (isinstance(value, self._klass) and ((str(value.geom_type).upper() == gtype) or (gtype == 'GEOMETRY'))): if (value.srid is None): value.srid = self._field.srid elif ((value is None) or isinstance(value, (six.string_types + (memoryview,)))): pass else: raise TypeError(('cannot set %s GeometryProxy with value of type: %s' % (obj.__class__.__name__, type(value)))) obj.__dict__[self._field.attname] = value return value
'The initialization function for geometry fields. Takes the following as keyword arguments: srid: The spatial reference system identifier, an OGC standard. Defaults to 4326 (WGS84). spatial_index: Indicates whether to create a spatial index. Defaults to True. Set this instead of \'db_index\' for geographic fields since index creation is different for geometry columns. dim: The number of dimensions for this geometry. Defaults to 2. extent: Customize the extent, in a 4-tuple of WGS 84 coordinates, for the geometry field entry in the `USER_SDO_GEOM_METADATA` table. Defaults to (-180.0, -90.0, 180.0, 90.0). tolerance: Define the tolerance, in meters, to use for the geometry field entry in the `USER_SDO_GEOM_METADATA` table. Defaults to 0.05.'
def __init__(self, verbose_name=None, srid=4326, spatial_index=True, dim=2, geography=False, **kwargs):
self.spatial_index = spatial_index self.srid = srid self.dim = dim kwargs['verbose_name'] = verbose_name self.geography = geography self._extent = kwargs.pop('extent', ((-180.0), (-90.0), 180.0, 90.0)) self._tolerance = kwargs.pop('tolerance', 0.05) super(GeometryField, self).__init__(**kwargs)
'Returns true if this field\'s SRID corresponds with a coordinate system that uses non-projected units (e.g., latitude/longitude).'
def geodetic(self, connection):
return (self.units_name(connection) in self.geodetic_units)
'Returns a distance number in units of the field. For example, if `D(km=1)` was passed in and the units of the field were in meters, then 1000 would be returned.'
def get_distance(self, value, lookup_type, connection):
return connection.ops.get_distance(self, value, lookup_type)
'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.'
def get_prep_value(self, value):
if isinstance(value, SQLEvaluator): return value elif isinstance(value, (tuple, list)): geom = value[0] seq_value = True else: geom = value seq_value = False 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__)) geom.srid = self.get_srid(geom) if seq_value: lookup_val = [geom] lookup_val.extend(value[1:]) return tuple(lookup_val) else: return geom
'Returns the default SRID for the given geometry, taking into account the SRID set for the field. For example, if the input geometry has no SRID, then that of the field will be returned.'
def get_srid(self, geom):
gsrid = geom.srid if ((gsrid is None) or (self.srid == (-1)) or ((gsrid == (-1)) and (self.srid != (-1)))): return self.srid else: return gsrid
'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.'
def get_db_prep_lookup(self, lookup_type, value, connection, prepared=False):
if (lookup_type in connection.ops.gis_terms): if (lookup_type == 'isnull'): return [] if isinstance(value, (tuple, list)): params = [connection.ops.Adapter(value[0])] if (lookup_type in connection.ops.distance_functions): params += self.get_distance(value[1:], lookup_type, connection) elif (lookup_type in connection.ops.truncate_params): pass else: params += value[1:] elif isinstance(value, SQLEvaluator): 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__)))
'Prepares the value for saving in the database.'
def get_db_prep_save(self, value, connection):
if (value is None): return None else: return connection.ops.Adapter(self.get_prep_value(value))
'Returns the placeholder for the geometry column for the given value.'
def get_placeholder(self, value, connection):
return connection.ops.get_geom_placeholder(self, value)
'Returns the area of the geographic field in an `area` attribute on each element of this GeoQuerySet.'
def area(self, tolerance=0.05, **kwargs):
(procedure_args, geo_field) = self._spatial_setup('area', field_name=kwargs.get('field_name', None)) s = {'procedure_args': procedure_args, 'geo_field': geo_field, 'setup': False} connection = connections[self.db] backend = connection.ops if backend.oracle: s['procedure_fmt'] = '%(geo_col)s,%(tolerance)s' s['procedure_args']['tolerance'] = tolerance s['select_field'] = AreaField('sq_m') elif (backend.postgis or backend.spatialite): if backend.geography: s['select_field'] = AreaField('sq_m') elif (not geo_field.geodetic(connection)): s['select_field'] = AreaField(Area.unit_attname(geo_field.units_name(connection))) else: raise Exception('Area on geodetic coordinate systems not supported.') return self._spatial_attribute('area', s, **kwargs)
'Returns the centroid of the geographic field in a `centroid` attribute on each element of this GeoQuerySet.'
def centroid(self, **kwargs):
return self._geom_attribute('centroid', **kwargs)
'Performs an aggregate collect operation on the given geometry field. This is analagous to a union operation, but much faster because boundaries are not dissolved.'
def collect(self, **kwargs):
return self._spatial_aggregate(aggregates.Collect, **kwargs)
'Returns the spatial difference of the geographic field in a `difference` attribute on each element of this GeoQuerySet.'
def difference(self, geom, **kwargs):
return self._geomset_attribute('difference', geom, **kwargs)
'Returns the distance from the given geographic field name to the given geometry in a `distance` attribute on each element of the GeoQuerySet. Keyword Arguments: `spheroid` => If the geometry field is geodetic and PostGIS is the spatial database, then the more accurate spheroid calculation will be used instead of the quicker sphere calculation. `tolerance` => Used only for Oracle. The tolerance is in meters -- a default of 5 centimeters (0.05) is used.'
def distance(self, geom, **kwargs):
return self._distance_attribute('distance', geom, **kwargs)
'Returns a Geometry representing the bounding box of the Geometry field in an `envelope` attribute on each element of the GeoQuerySet.'
def envelope(self, **kwargs):
return self._geom_attribute('envelope', **kwargs)
'Returns the extent (aggregate) of the features in the GeoQuerySet. The extent will be returned as a 4-tuple, consisting of (xmin, ymin, xmax, ymax).'
def extent(self, **kwargs):
return self._spatial_aggregate(aggregates.Extent, **kwargs)
'Returns the aggregate extent, in 3D, of the features in the GeoQuerySet. It is returned as a 6-tuple, comprising: (xmin, ymin, zmin, xmax, ymax, zmax).'
def extent3d(self, **kwargs):
return self._spatial_aggregate(aggregates.Extent3D, **kwargs)
'Returns a modified version of the Polygon/MultiPolygon in which all of the vertices follow the Right-Hand-Rule. By default, this is attached as the `force_rhr` attribute on each element of the GeoQuerySet.'
def force_rhr(self, **kwargs):
return self._geom_attribute('force_rhr', **kwargs)
'Returns a GeoJSON representation of the geomtry field in a `geojson` attribute on each element of the GeoQuerySet. The `crs` and `bbox` keywords may be set to True if the users wants the coordinate reference system and the bounding box to be included in the GeoJSON representation of the geometry.'
def geojson(self, precision=8, crs=False, bbox=False, **kwargs):
backend = connections[self.db].ops if (not backend.geojson): raise NotImplementedError('Only PostGIS 1.3.4+ and SpatiaLite 3.0+ support GeoJSON serialization.') if (not isinstance(precision, six.integer_types)): raise TypeError('Precision keyword must be set with an integer.') if (backend.spatial_version >= (1, 4, 0)): options = 0 if (crs and bbox): options = 3 elif bbox: options = 1 elif crs: options = 2 else: options = 0 if (crs and bbox): options = 3 elif crs: options = 1 elif bbox: options = 2 s = {'desc': 'GeoJSON', 'procedure_args': {'precision': precision, 'options': options}, 'procedure_fmt': '%(geo_col)s,%(precision)s,%(options)s'} return self._spatial_attribute('geojson', s, **kwargs)
'Returns a GeoHash representation of the given field in a `geohash` attribute on each element of the GeoQuerySet. The `precision` keyword may be used to custom the number of _characters_ used in the output GeoHash, the default is 20.'
def geohash(self, precision=20, **kwargs):
s = {'desc': 'GeoHash', 'procedure_args': {'precision': precision}, 'procedure_fmt': '%(geo_col)s,%(precision)s'} return self._spatial_attribute('geohash', s, **kwargs)
'Returns GML representation of the given field in a `gml` attribute on each element of the GeoQuerySet.'
def gml(self, precision=8, version=2, **kwargs):
backend = connections[self.db].ops s = {'desc': 'GML', 'procedure_args': {'precision': precision}} if backend.postgis: if (backend.spatial_version > (1, 3, 1)): s['procedure_fmt'] = '%(version)s,%(geo_col)s,%(precision)s' else: s['procedure_fmt'] = '%(geo_col)s,%(precision)s,%(version)s' s['procedure_args'] = {'precision': precision, 'version': version} return self._spatial_attribute('gml', s, **kwargs)
'Returns the spatial intersection of the Geometry field in an `intersection` attribute on each element of this GeoQuerySet.'
def intersection(self, geom, **kwargs):
return self._geomset_attribute('intersection', geom, **kwargs)
'Returns KML representation of the geometry field in a `kml` attribute on each element of this GeoQuerySet.'
def kml(self, **kwargs):
s = {'desc': 'KML', 'procedure_fmt': '%(geo_col)s,%(precision)s', 'procedure_args': {'precision': kwargs.pop('precision', 8)}} return self._spatial_attribute('kml', s, **kwargs)
'Returns the length of the geometry field as a `Distance` object stored in a `length` attribute on each element of this GeoQuerySet.'
def length(self, **kwargs):
return self._distance_attribute('length', None, **kwargs)
'Creates a linestring from all of the PointField geometries in the this GeoQuerySet and returns it. This is a spatial aggregate method, and thus returns a geometry rather than a GeoQuerySet.'
def make_line(self, **kwargs):
return self._spatial_aggregate(aggregates.MakeLine, geo_field_type=PointField, **kwargs)
'Returns the memory size (number of bytes) that the geometry field takes in a `mem_size` attribute on each element of this GeoQuerySet.'
def mem_size(self, **kwargs):
return self._spatial_attribute('mem_size', {}, **kwargs)
'Returns the number of geometries if the field is a GeometryCollection or Multi* Field in a `num_geom` attribute on each element of this GeoQuerySet; otherwise the sets with None.'
def num_geom(self, **kwargs):
return self._spatial_attribute('num_geom', {}, **kwargs)
'Returns the number of points in the first linestring in the Geometry field in a `num_points` attribute on each element of this GeoQuerySet; otherwise sets with None.'
def num_points(self, **kwargs):
return self._spatial_attribute('num_points', {}, **kwargs)
'Returns the perimeter of the geometry field as a `Distance` object stored in a `perimeter` attribute on each element of this GeoQuerySet.'
def perimeter(self, **kwargs):
return self._distance_attribute('perimeter', None, **kwargs)
'Returns a Point geometry guaranteed to lie on the surface of the Geometry field in a `point_on_surface` attribute on each element of this GeoQuerySet; otherwise sets with None.'
def point_on_surface(self, **kwargs):
return self._geom_attribute('point_on_surface', **kwargs)
'Reverses the coordinate order of the geometry, and attaches as a `reverse` attribute on each element of this GeoQuerySet.'
def reverse_geom(self, **kwargs):
s = {'select_field': GeomField()} kwargs.setdefault('model_att', 'reverse_geom') if connections[self.db].ops.oracle: s['geo_field_type'] = LineStringField return self._spatial_attribute('reverse', s, **kwargs)
'Scales the geometry to a new size by multiplying the ordinates with the given x,y,z scale factors.'
def scale(self, x, y, z=0.0, **kwargs):
if connections[self.db].ops.spatialite: if (z != 0.0): raise NotImplementedError('SpatiaLite does not support 3D scaling.') s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s', 'procedure_args': {'x': x, 'y': y}, 'select_field': GeomField()} else: s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s,%(z)s', 'procedure_args': {'x': x, 'y': y, 'z': z}, 'select_field': GeomField()} return self._spatial_attribute('scale', s, **kwargs)
'Snap all points of the input geometry to the grid. How the geometry is snapped to the grid depends on how many arguments were given: - 1 argument : A single size to snap both the X and Y grids to. - 2 arguments: X and Y sizes to snap the grid to. - 4 arguments: X, Y sizes and the X, Y origins.'
def snap_to_grid(self, *args, **kwargs):
if (False in [isinstance(arg, ((float,) + six.integer_types)) for arg in args]): raise TypeError('Size argument(s) for the grid must be a float or integer values.') nargs = len(args) if (nargs == 1): size = args[0] procedure_fmt = '%(geo_col)s,%(size)s' procedure_args = {'size': size} elif (nargs == 2): (xsize, ysize) = args procedure_fmt = '%(geo_col)s,%(xsize)s,%(ysize)s' procedure_args = {'xsize': xsize, 'ysize': ysize} elif (nargs == 4): (xsize, ysize, xorigin, yorigin) = args procedure_fmt = '%(geo_col)s,%(xorigin)s,%(yorigin)s,%(xsize)s,%(ysize)s' procedure_args = {'xsize': xsize, 'ysize': ysize, 'xorigin': xorigin, 'yorigin': yorigin} else: raise ValueError('Must provide 1, 2, or 4 arguments to `snap_to_grid`.') s = {'procedure_fmt': procedure_fmt, 'procedure_args': procedure_args, 'select_field': GeomField()} return self._spatial_attribute('snap_to_grid', s, **kwargs)
'Returns SVG representation of the geographic field in a `svg` attribute on each element of this GeoQuerySet. Keyword Arguments: `relative` => If set to True, this will evaluate the path in terms of relative moves (rather than absolute). `precision` => May be used to set the maximum number of decimal digits used in output (defaults to 8).'
def svg(self, relative=False, precision=8, **kwargs):
relative = int(bool(relative)) if (not isinstance(precision, six.integer_types)): raise TypeError('SVG precision keyword argument must be an integer.') s = {'desc': 'SVG', 'procedure_fmt': '%(geo_col)s,%(rel)s,%(precision)s', 'procedure_args': {'rel': relative, 'precision': precision}} return self._spatial_attribute('svg', s, **kwargs)
'Returns the symmetric difference of the geographic field in a `sym_difference` attribute on each element of this GeoQuerySet.'
def sym_difference(self, geom, **kwargs):
return self._geomset_attribute('sym_difference', geom, **kwargs)
'Translates the geometry to a new location using the given numeric parameters as offsets.'
def translate(self, x, y, z=0.0, **kwargs):
if connections[self.db].ops.spatialite: if (z != 0.0): raise NotImplementedError('SpatiaLite does not support 3D translation.') s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s', 'procedure_args': {'x': x, 'y': y}, 'select_field': GeomField()} else: s = {'procedure_fmt': '%(geo_col)s,%(x)s,%(y)s,%(z)s', 'procedure_args': {'x': x, 'y': y, 'z': z}, 'select_field': GeomField()} return self._spatial_attribute('translate', s, **kwargs)
'Transforms the given geometry field to the given SRID. If no SRID is provided, the transformation will default to using 4326 (WGS84).'
def transform(self, srid=4326, **kwargs):
if (not isinstance(srid, six.integer_types)): raise TypeError('An integer SRID must be provided.') field_name = kwargs.get('field_name', None) (tmp, geo_field) = self._spatial_setup('transform', field_name=field_name) field_col = self._geocol_select(geo_field, field_name) geo_col = self.query.custom_select.get(geo_field, field_col) custom_sel = ('%s(%s, %s)' % (connections[self.db].ops.transform, geo_col, srid)) self.query.transformed_srid = srid self.query.custom_select[geo_field] = custom_sel return self._clone()
'Returns the union of the geographic field with the given Geometry in a `union` attribute on each element of this GeoQuerySet.'
def union(self, geom, **kwargs):
return self._geomset_attribute('union', geom, **kwargs)
'Performs an aggregate union on the given geometry field. Returns None if the GeoQuerySet is empty. The `tolerance` keyword is for Oracle backends only.'
def unionagg(self, **kwargs):
return self._spatial_aggregate(aggregates.Union, **kwargs)
'Performs set up for executing the spatial function.'
def _spatial_setup(self, att, desc=None, field_name=None, geo_field_type=None):
connection = connections[self.db] func = getattr(connection.ops, att, False) if (desc is None): desc = att if (not func): raise NotImplementedError(('%s stored procedure not available on the %s backend.' % (desc, connection.ops.name))) procedure_args = {'function': func} geo_field = self.query._geo_field(field_name) if (not geo_field): raise TypeError(('%s output only available on GeometryFields.' % func)) if ((not (geo_field_type is None)) and (not isinstance(geo_field, geo_field_type))): raise TypeError(('"%s" stored procedures may only be called on %ss.' % (func, geo_field_type.__name__))) procedure_args['geo_col'] = self._geocol_select(geo_field, field_name) return (procedure_args, geo_field)
'DRY routine for calling aggregate spatial stored procedures and returning their result to the caller of the function.'
def _spatial_aggregate(self, aggregate, field_name=None, geo_field_type=None, tolerance=0.05):
geo_field = self.query._geo_field(field_name) if (not geo_field): raise TypeError(('%s aggregate only available on GeometryFields.' % aggregate.name)) if ((not (geo_field_type is None)) and (not isinstance(geo_field, geo_field_type))): raise TypeError(('%s aggregate may only be called on %ss.' % (aggregate.name, geo_field_type.__name__))) agg_col = (field_name or geo_field.name) agg_kwargs = {} if connections[self.db].ops.oracle: agg_kwargs['tolerance'] = tolerance return self.aggregate(geoagg=aggregate(agg_col, **agg_kwargs))['geoagg']
'DRY routine for calling a spatial stored procedure on a geometry column and attaching its output as an attribute of the model. Arguments: att: The name of the spatial attribute that holds the spatial SQL function to call. settings: Dictonary of internal settings to customize for the spatial procedure. Public Keyword Arguments: field_name: The name of the geographic field to call the spatial function on. May also be a lookup to a geometry field as part of a foreign key relation. model_att: The name of the model attribute to attach the output of the spatial function to.'
def _spatial_attribute(self, att, settings, field_name=None, model_att=None):
settings.setdefault('desc', None) settings.setdefault('geom_args', ()) settings.setdefault('geom_field', None) settings.setdefault('procedure_args', {}) settings.setdefault('procedure_fmt', '%(geo_col)s') settings.setdefault('select_params', []) connection = connections[self.db] backend = connection.ops if settings.get('setup', True): (default_args, geo_field) = self._spatial_setup(att, desc=settings['desc'], field_name=field_name, geo_field_type=settings.get('geo_field_type', None)) for (k, v) in six.iteritems(default_args): settings['procedure_args'].setdefault(k, v) else: geo_field = settings['geo_field'] if (not isinstance(model_att, six.string_types)): model_att = att for name in settings['geom_args']: geom = geo_field.get_prep_value(settings['procedure_args'][name]) params = geo_field.get_db_prep_lookup('contains', geom, connection=connection) geom_placeholder = geo_field.get_placeholder(geom, connection) old_fmt = ('%%(%s)s' % name) new_fmt = (geom_placeholder % '%%s') settings['procedure_fmt'] = settings['procedure_fmt'].replace(old_fmt, new_fmt) settings['select_params'].extend(params) fmt = ('%%(function)s(%s)' % settings['procedure_fmt']) if settings.get('select_field', False): sel_fld = settings['select_field'] if (isinstance(sel_fld, GeomField) and backend.select): self.query.custom_select[model_att] = backend.select if connection.ops.oracle: sel_fld.empty_strings_allowed = False self.query.extra_select_fields[model_att] = sel_fld return self.extra(select={model_att: (fmt % settings['procedure_args'])}, select_params=settings['select_params'])
'DRY routine for GeoQuerySet distance attribute routines.'
def _distance_attribute(self, func, geom=None, tolerance=0.05, spheroid=False, **kwargs):
(procedure_args, geo_field) = self._spatial_setup(func, field_name=kwargs.get('field_name', None)) connection = connections[self.db] geodetic = geo_field.geodetic(connection) geography = geo_field.geography if geodetic: dist_att = 'm' else: dist_att = Distance.unit_attname(geo_field.units_name(connection)) distance = (func == 'distance') length = (func == 'length') perimeter = (func == 'perimeter') if (not (distance or length or perimeter)): raise ValueError(('Unknown distance function: %s' % func)) geom_3d = (geo_field.dim == 3) lookup_params = [(geom or 'POINT (0 0)'), 0] backend = connection.ops if (spheroid or (backend.postgis and geodetic and (not geography) and length)): lookup_params.append('spheroid') lookup_params = geo_field.get_prep_value(lookup_params) params = geo_field.get_db_prep_lookup('distance_lte', lookup_params, connection=connection) geom_args = bool(geom) if backend.oracle: if distance: procedure_fmt = '%(geo_col)s,%(geom)s,%(tolerance)s' elif (length or perimeter): procedure_fmt = '%(geo_col)s,%(tolerance)s' procedure_args['tolerance'] = tolerance else: if self.query.transformed_srid: (u, unit_name, s) = get_srid_info(self.query.transformed_srid, connection) geodetic = (unit_name in geo_field.geodetic_units) if (backend.spatialite and geodetic): raise ValueError('SQLite does not support linear distance calculations on geodetic coordinate systems.') if distance: if self.query.transformed_srid: geom_args = False procedure_fmt = ('%s(%%(geo_col)s, %s)' % (backend.transform, self.query.transformed_srid)) if ((geom.srid is None) or (geom.srid == self.query.transformed_srid)): if backend.spatialite: procedure_fmt += (', %s(%%%%s, %s)' % (backend.from_text, self.query.transformed_srid)) else: procedure_fmt += ', %%s' elif backend.spatialite: procedure_fmt += (', %s(%s(%%%%s, %s), %s)' % (backend.transform, backend.from_text, geom.srid, self.query.transformed_srid)) else: procedure_fmt += (', %s(%%%%s, %s)' % (backend.transform, self.query.transformed_srid)) else: procedure_fmt = '%(geo_col)s,%(geom)s' if ((not geography) and geodetic): if (not backend.geography): if (not isinstance(geo_field, PointField)): raise ValueError('Spherical distance calculation only supported on PointFields.') if (not (str(Geometry(memoryview(params[0].ewkb)).geom_type) == 'Point')): raise ValueError('Spherical distance calculation only supported with Point Geometry parameters') if spheroid: procedure_fmt += ",'%(spheroid)s'" procedure_args.update({'function': backend.distance_spheroid, 'spheroid': params[1]}) else: procedure_args.update({'function': backend.distance_sphere}) elif (length or perimeter): procedure_fmt = '%(geo_col)s' if ((not geography) and geodetic and length): procedure_fmt += ",'%(spheroid)s'" procedure_args.update({'function': backend.length_spheroid, 'spheroid': params[1]}) elif (geom_3d and backend.postgis): if perimeter: procedure_args.update({'function': backend.perimeter3d}) elif length: procedure_args.update({'function': backend.length3d}) s = {'select_field': DistanceField(dist_att), 'setup': False, 'geo_field': geo_field, 'procedure_args': procedure_args, 'procedure_fmt': procedure_fmt} if geom_args: s['geom_args'] = ('geom',) s['procedure_args']['geom'] = geom elif geom: s['select_params'] = [backend.Adapter(geom)] return self._spatial_attribute(func, s, **kwargs)
'DRY routine for setting up a GeoQuerySet method that attaches a Geometry attribute (e.g., `centroid`, `point_on_surface`).'
def _geom_attribute(self, func, tolerance=0.05, **kwargs):
s = {'select_field': GeomField()} if connections[self.db].ops.oracle: s['procedure_fmt'] = '%(geo_col)s,%(tolerance)s' s['procedure_args'] = {'tolerance': tolerance} return self._spatial_attribute(func, s, **kwargs)
'DRY routine for setting up a GeoQuerySet method that attaches a Geometry attribute and takes a Geoemtry parameter. This is used for geometry set-like operations (e.g., intersection, difference, union, sym_difference).'
def _geomset_attribute(self, func, geom, tolerance=0.05, **kwargs):
s = {'geom_args': ('geom',), 'select_field': GeomField(), 'procedure_fmt': '%(geo_col)s,%(geom)s', 'procedure_args': {'geom': geom}} if connections[self.db].ops.oracle: s['procedure_fmt'] += ',%(tolerance)s' s['procedure_args']['tolerance'] = tolerance return self._spatial_attribute(func, s, **kwargs)
'Helper routine for constructing the SQL to select the geographic column. Takes into account if the geographic field is in a ForeignKey relation to the current model.'
def _geocol_select(self, geo_field, field_name):
opts = self.model._meta if (not (geo_field in opts.fields)): self.query.add_select_related([field_name]) compiler = self.query.get_compiler(self.db) compiler.pre_sql_setup() (rel_table, rel_col) = self.query.related_select_cols[self.query.related_select_fields.index(geo_field)] return compiler._field_column(geo_field, rel_table) elif (not (geo_field in opts.local_fields)): (tmp_fld, parent_model, direct, m2m) = opts.get_field_by_name(geo_field.name) return self.query.get_compiler(self.db)._field_column(geo_field, parent_model._meta.db_table) else: return self.query.get_compiler(self.db)._field_column(geo_field)
'Utility for checking the given lookup with the given model options. The lookup is a string either specifying the geographic field, e.g. \'point, \'the_geom\', or a related lookup on a geographic field like \'address__point\'. If a GeometryField exists according to the given lookup on the model options, it will be returned. Otherwise returns None.'
@classmethod def _check_geo_field(cls, opts, lookup):
field_list = lookup.split(LOOKUP_SEP) field_list.reverse() fld_name = field_list.pop() try: geo_fld = opts.get_field(fld_name) while len(field_list): opts = geo_fld.rel.to._meta geo_fld = opts.get_field(field_list.pop()) except (FieldDoesNotExist, AttributeError): return False if isinstance(geo_fld, GeometryField): return geo_fld else: return False
'Overloaded method so OracleQuery.convert_values doesn\'t balk.'
def get_internal_type(self):
return None
'Using the same routines that Oracle does we can convert our extra selection objects into Geometry and Distance objects. TODO: Make converted objects \'lazy\' for less overhead.'
def convert_values(self, value, field, connection):
if connection.ops.oracle: value = super(GeoQuery, self).convert_values(value, (field or GeomField()), connection) if (value is None): pass elif isinstance(field, DistanceField): value = Distance(**{field.distance_att: value}) elif isinstance(field, AreaField): value = Area(**{field.area_att: value}) elif (isinstance(field, (GeomField, GeometryField)) and value): value = Geometry(value) elif (field is not None): return super(GeoQuery, self).convert_values(value, field, connection) return value
'Overridden from GeoQuery\'s normalize to handle the conversion of GeoAggregate objects.'
def resolve_aggregate(self, value, aggregate, connection):
if isinstance(aggregate, self.aggregates_module.GeoAggregate): if aggregate.is_extent: if (aggregate.is_extent == '3D'): return connection.ops.convert_extent3d(value) else: return connection.ops.convert_extent(value) else: return connection.ops.convert_geom(value, aggregate.source) else: return super(GeoQuery, self).resolve_aggregate(value, aggregate, connection)
'Returns the first Geometry field encountered; or specified via the `field_name` keyword. The `field_name` may be a string specifying the geometry field on this GeoQuery\'s model, or a lookup string to a geometry field via a ForeignKey relation.'
def _geo_field(self, field_name=None):
if (field_name is None): for fld in self.model._meta.fields: if isinstance(fld, GeometryField): return fld return False else: return GeoWhereNode._check_geo_field(self.model._meta, field_name)
'Return the aggregate, rendered as SQL.'
def as_sql(self, qn, connection):
if connection.ops.oracle: self.extra['tolerance'] = self.tolerance if hasattr(self.col, 'as_sql'): field_name = self.col.as_sql(qn, connection) elif isinstance(self.col, (list, tuple)): field_name = '.'.join([qn(c) for c in self.col]) else: field_name = self.col (sql_template, sql_function) = connection.ops.spatial_aggregate_sql(self) params = {'function': sql_function, 'field': field_name} params.update(self.extra) return (sql_template % params)
'Return the list of columns to use in the select statement. If no columns have been specified, returns all columns relating to fields in the model. If \'with_aliases\' is true, any column names that are duplicated (without the table names) are given unique aliases. This is needed in some cases to avoid ambiguitity with nested queries. This routine is overridden from Query to handle customized selection of geometry columns.'
def get_columns(self, with_aliases=False):
qn = self.quote_name_unless_alias qn2 = self.connection.ops.quote_name result = [('(%s) AS %s' % ((self.get_extra_select_format(alias) % col[0]), qn2(alias))) for (alias, col) in six.iteritems(self.query.extra_select)] aliases = set(self.query.extra_select.keys()) if with_aliases: col_aliases = aliases.copy() else: col_aliases = set() if self.query.select: only_load = self.deferred_to_columns() for (col, field) in zip(self.query.select, self.query.select_fields): if isinstance(col, (list, tuple)): (alias, column) = col table = self.query.alias_map[alias].table_name if ((table in only_load) and (column not in only_load[table])): continue r = self.get_field_select(field, alias, column) if with_aliases: if (col[1] in col_aliases): c_alias = ('Col%d' % len(col_aliases)) result.append(('%s AS %s' % (r, c_alias))) aliases.add(c_alias) col_aliases.add(c_alias) else: result.append(('%s AS %s' % (r, qn2(col[1])))) aliases.add(r) col_aliases.add(col[1]) else: result.append(r) aliases.add(r) col_aliases.add(col[1]) else: result.append(col.as_sql(qn, self.connection)) if hasattr(col, 'alias'): aliases.add(col.alias) col_aliases.add(col.alias) elif self.query.default_cols: (cols, new_aliases) = self.get_default_columns(with_aliases, col_aliases) result.extend(cols) aliases.update(new_aliases) max_name_length = self.connection.ops.max_name_length() result.extend([('%s%s' % ((self.get_extra_select_format(alias) % aggregate.as_sql(qn, self.connection)), (((alias is not None) and (' AS %s' % qn(truncate_name(alias, max_name_length)))) or ''))) for (alias, aggregate) in self.query.aggregate_select.items()]) for ((table, col), field) in zip(self.query.related_select_cols, self.query.related_select_fields): r = self.get_field_select(field, table, col) if (with_aliases and (col in col_aliases)): c_alias = ('Col%d' % len(col_aliases)) result.append(('%s AS %s' % (r, c_alias))) aliases.add(c_alias) col_aliases.add(c_alias) else: result.append(r) aliases.add(r) col_aliases.add(col) self._select_aliases = aliases return result
'Computes the default columns for selecting every field in the base model. Will sometimes be called to pull in related models (e.g. via select_related), in which case "opts" and "start_alias" will be given to provide a starting point for the traversal. Returns a list of strings, quoted appropriately for use in SQL directly, as well as a set of aliases used in the select statement (if \'as_pairs\' is True, returns a list of (alias, col_name) pairs instead of strings as the first component and None as the second component). This routine is overridden from Query to handle customized selection of geometry columns.'
def get_default_columns(self, with_aliases=False, col_aliases=None, start_alias=None, opts=None, as_pairs=False, local_only=False):
result = [] if (opts is None): opts = self.query.model._meta aliases = set() only_load = self.deferred_to_columns() if start_alias: seen = {None: start_alias} for (field, model) in opts.get_fields_with_model(): if (model == opts.concrete_model): model = None if (local_only and (model is not None)): continue if start_alias: try: alias = seen[model] except KeyError: link_field = opts.get_ancestor_link(model) alias = self.query.join((start_alias, model._meta.db_table, link_field.column, model._meta.pk.column)) seen[model] = alias else: alias = self.query.included_inherited_models[model] table = self.query.alias_map[alias].table_name if ((table in only_load) and (field.column not in only_load[table])): continue if as_pairs: result.append((alias, field.column)) aliases.add(alias) continue field_sel = self.get_field_select(field, alias) if (with_aliases and (field.column in col_aliases)): c_alias = ('Col%d' % len(col_aliases)) result.append(('%s AS %s' % (field_sel, c_alias))) col_aliases.add(c_alias) aliases.add(c_alias) else: r = field_sel result.append(r) aliases.add(r) if with_aliases: col_aliases.add(field.column) return (result, aliases)
'This routine is necessary so that distances and geometries returned from extra selection SQL get resolved appropriately into Python objects.'
def resolve_columns(self, row, fields=()):
values = [] aliases = list(self.query.extra_select) rn_offset = 0 if self.connection.ops.oracle: if ((self.query.high_mark is not None) or self.query.low_mark): rn_offset = 1 index_start = (rn_offset + len(aliases)) values = [self.query.convert_values(v, self.query.extra_select_fields.get(a, None), self.connection) for (v, a) in zip(row[rn_offset:index_start], aliases)] if (self.connection.ops.oracle or getattr(self.query, 'geo_values', False)): for (value, field) in zip_longest(row[index_start:], fields): values.append(self.query.convert_values(value, field, self.connection)) else: values.extend(row[index_start:]) return tuple(values)
'Returns the SELECT SQL string for the given field. Figures out if any custom selection SQL is needed for the column The `alias` keyword may be used to manually specify the database table where the column exists, if not in the model associated with this `GeoQuery`. Similarly, `column` may be used to specify the exact column name, rather than using the `column` attribute on `field`.'
def get_field_select(self, field, alias=None, column=None):
sel_fmt = self.get_select_format(field) if (field in self.query.custom_select): field_sel = (sel_fmt % self.query.custom_select[field]) else: field_sel = (sel_fmt % self._field_column(field, alias, column)) return field_sel
'Returns the selection format string, depending on the requirements of the spatial backend. For example, Oracle and MySQL require custom selection formats in order to retrieve geometries in OGC WKT. For all other fields a simple \'%s\' format string is returned.'
def get_select_format(self, fld):
if (self.connection.ops.select and hasattr(fld, 'geom_type')): sel_fmt = self.connection.ops.select if (self.query.transformed_srid and (self.connection.ops.oracle or self.connection.ops.spatialite)): sel_fmt = ("'SRID=%d;'||%s" % (self.query.transformed_srid, sel_fmt)) else: sel_fmt = '%s' return sel_fmt