You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

geojson.py 2.6KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. from django.contrib.gis.gdal import CoordTransform, SpatialReference
  2. from django.core.serializers.base import SerializerDoesNotExist
  3. from django.core.serializers.json import Serializer as JSONSerializer
  4. class Serializer(JSONSerializer):
  5. """
  6. Convert a queryset to GeoJSON, http://geojson.org/
  7. """
  8. def _init_options(self):
  9. super()._init_options()
  10. self.geometry_field = self.json_kwargs.pop('geometry_field', None)
  11. self.srid = self.json_kwargs.pop('srid', 4326)
  12. if (self.selected_fields is not None and self.geometry_field is not None and
  13. self.geometry_field not in self.selected_fields):
  14. self.selected_fields = [*self.selected_fields, self.geometry_field]
  15. def start_serialization(self):
  16. self._init_options()
  17. self._cts = {} # cache of CoordTransform's
  18. self.stream.write(
  19. '{"type": "FeatureCollection", "crs": {"type": "name", "properties": {"name": "EPSG:%d"}},'
  20. ' "features": [' % self.srid)
  21. def end_serialization(self):
  22. self.stream.write(']}')
  23. def start_object(self, obj):
  24. super().start_object(obj)
  25. self._geometry = None
  26. if self.geometry_field is None:
  27. # Find the first declared geometry field
  28. for field in obj._meta.fields:
  29. if hasattr(field, 'geom_type'):
  30. self.geometry_field = field.name
  31. break
  32. def get_dump_object(self, obj):
  33. data = {
  34. "type": "Feature",
  35. "properties": self._current,
  36. }
  37. if ((self.selected_fields is None or 'pk' in self.selected_fields) and
  38. 'pk' not in data["properties"]):
  39. data["properties"]["pk"] = obj._meta.pk.value_to_string(obj)
  40. if self._geometry:
  41. if self._geometry.srid != self.srid:
  42. # If needed, transform the geometry in the srid of the global geojson srid
  43. if self._geometry.srid not in self._cts:
  44. srs = SpatialReference(self.srid)
  45. self._cts[self._geometry.srid] = CoordTransform(self._geometry.srs, srs)
  46. self._geometry.transform(self._cts[self._geometry.srid])
  47. data["geometry"] = eval(self._geometry.geojson)
  48. else:
  49. data["geometry"] = None
  50. return data
  51. def handle_field(self, obj, field):
  52. if field.name == self.geometry_field:
  53. self._geometry = field.value_from_object(obj)
  54. else:
  55. super().handle_field(obj, field)
  56. class Deserializer:
  57. def __init__(self, *args, **kwargs):
  58. raise SerializerDoesNotExist("geojson is a serialization-only serializer")