Skip to content
Branch: master
Find file Copy path
Find file Copy path
Fetching contributors…
Cannot retrieve contributors at this time
68 lines (58 sloc) 2.65 KB
from django.contrib.gis.gdal import CoordTransform, SpatialReference
from django.core.serializers.base import SerializerDoesNotExist
from django.core.serializers.json import Serializer as JSONSerializer
class Serializer(JSONSerializer):
Convert a queryset to GeoJSON,
def _init_options(self):
self.geometry_field = self.json_kwargs.pop('geometry_field', None)
self.srid = self.json_kwargs.pop('srid', 4326)
if (self.selected_fields is not None and self.geometry_field is not None and
self.geometry_field not in self.selected_fields):
self.selected_fields = [*self.selected_fields, self.geometry_field]
def start_serialization(self):
self._cts = {} # cache of CoordTransform's
'{"type": "FeatureCollection", "crs": {"type": "name", "properties": {"name": "EPSG:%d"}},'
' "features": [' % self.srid)
def end_serialization(self):']}')
def start_object(self, obj):
self._geometry = None
if self.geometry_field is None:
# Find the first declared geometry field
for field in obj._meta.fields:
if hasattr(field, 'geom_type'):
self.geometry_field =
def get_dump_object(self, obj):
data = {
"type": "Feature",
"properties": self._current,
if ((self.selected_fields is None or 'pk' in self.selected_fields) and
'pk' not in data["properties"]):
data["properties"]["pk"] =
if self._geometry:
if self._geometry.srid != self.srid:
# If needed, transform the geometry in the srid of the global geojson srid
if self._geometry.srid not in self._cts:
srs = SpatialReference(self.srid)
self._cts[self._geometry.srid] = CoordTransform(self._geometry.srs, srs)
data["geometry"] = eval(self._geometry.geojson)
data["geometry"] = None
return data
def handle_field(self, obj, field):
if == self.geometry_field:
self._geometry = field.value_from_object(obj)
super().handle_field(obj, field)
class Deserializer:
def __init__(self, *args, **kwargs):
raise SerializerDoesNotExist("geojson is a serialization-only serializer")
You can’t perform that action at this time.