App Engine Python SDK version 1.7.4 (2)
[gae.git] / python / lib / django_1_4 / django / contrib / gis / db / models / proxy.py
blobe569dd5c4fa1db5d6a41ba972190ede8cb342b62
1 """
2 The GeometryProxy object, allows for lazy-geometries. The proxy uses
3 Python descriptors for instantiating and setting Geometry objects
4 corresponding to geographic model fields.
6 Thanks to Robert Coup for providing this functionality (see #4322).
7 """
9 class GeometryProxy(object):
10 def __init__(self, klass, field):
11 """
12 Proxy initializes on the given Geometry class (not an instance) and
13 the GeometryField.
14 """
15 self._field = field
16 self._klass = klass
18 def __get__(self, obj, type=None):
19 """
20 This accessor retrieves the geometry, initializing it using the geometry
21 class specified during initialization and the HEXEWKB value of the field.
22 Currently, only GEOS or OGR geometries are supported.
23 """
24 if obj is None:
25 # Accessed on a class, not an instance
26 return self
28 # Getting the value of the field.
29 geom_value = obj.__dict__[self._field.attname]
31 if isinstance(geom_value, self._klass):
32 geom = geom_value
33 elif (geom_value is None) or (geom_value==''):
34 geom = None
35 else:
36 # Otherwise, a Geometry object is built using the field's contents,
37 # and the model's corresponding attribute is set.
38 geom = self._klass(geom_value)
39 setattr(obj, self._field.attname, geom)
40 return geom
42 def __set__(self, obj, value):
43 """
44 This accessor sets the proxied geometry with the geometry class
45 specified during initialization. Values of None, HEXEWKB, or WKT may
46 be used to set the geometry as well.
47 """
48 # The OGC Geometry type of the field.
49 gtype = self._field.geom_type
51 # The geometry type must match that of the field -- unless the
52 # general GeometryField is used.
53 if isinstance(value, self._klass) and (str(value.geom_type).upper() == gtype or gtype == 'GEOMETRY'):
54 # Assigning the SRID to the geometry.
55 if value.srid is None: value.srid = self._field.srid
56 elif value is None or isinstance(value, (basestring, buffer)):
57 # Set with None, WKT, HEX, or WKB
58 pass
59 else:
60 raise TypeError('cannot set %s GeometryProxy with value of type: %s' % (obj.__class__.__name__, type(value)))
62 # Setting the objects dictionary with the value, and returning.
63 obj.__dict__[self._field.attname] = value
64 return value