Debian Codegraph @

django/contrib/gis/db/models/proxy.py

raw
1 """
2 The SpatialProxy object allows for lazy-geometries and lazy-rasters. The proxy
3 uses Python descriptors for instantiating and setting Geometry or Raster
4 objects corresponding to geographic model fields.
5
6 Thanks to Robert Coup for providing this functionality (see #4322).
7 """
8
9 from django.db.models.query_utils import DeferredAttribute
10
11
12 class SpatialProxy(DeferredAttribute):
13 def __init__(self, klass, field, load_func=None):
14 """
15 Initialize on the given Geometry or Raster class (not an instance)
16 and the corresponding field.
17 """
18 self._klass = klass
19 self._load_func = load_func or klass
20 super().__init__(field)
21
22 def __get__(self, instance, cls=None):
23 """
24 Retrieve the geometry or raster, initializing it using the
25 corresponding class specified during initialization and the value of
26 the field. Currently, GEOS or OGR geometries as well as GDALRasters are
27 supported.
28 """
29 if instance is None:
30 # Accessed on a class, not an instance
31 return self
32
33 # Getting the value of the field.
34 try:
35 geo_value = instance.__dict__[self.field.attname]
36 except KeyError:
37 geo_value = super().__get__(instance, cls)
38
39 if isinstance(geo_value, self._klass):
40 geo_obj = geo_value
41 elif (geo_value is None) or (geo_value == ""):
42 geo_obj = None
43 else:
44 # Otherwise, a geometry or raster object is built using the field's
45 # contents, and the model's corresponding attribute is set.
46 geo_obj = self._load_func(geo_value)
47 setattr(instance, self.field.attname, geo_obj)
48 return geo_obj
49
50 def __set__(self, instance, value):
51 """
52 Retrieve the proxied geometry or raster with the corresponding class
53 specified during initialization.
54
55 To set geometries, use values of None, HEXEWKB, or WKT.
56 To set rasters, use JSON or dict values.
57 """
58 # The geographic type of the field.
59 gtype = self.field.geom_type
60
61 if gtype == "RASTER" and (
62 value is None or isinstance(value, (str, dict, self._klass))
63 ):
64 # For raster fields, ensure input is None or a string, dict, or
65 # raster instance.
66 pass
67 elif isinstance(value, self._klass):
68 # The geometry type must match that of the field -- unless the
69 # general GeometryField is used.
70 if value.srid is None:
71 # Assigning the field SRID if the geometry has no SRID.
72 value.srid = self.field.srid
73 elif value is None or isinstance(value, (str, memoryview)):
74 # Set geometries with None, WKT, HEX, or WKB
75 pass
76 else:
77 raise TypeError(
78 "Cannot set %s SpatialProxy (%s) with value of type: %s"
79 % (instance.__class__.__name__, gtype, type(value))
80 )
81
82 # Setting the objects dictionary with the value, and returning.
83 instance.__dict__[self.field.attname] = value
84 return value