| 1 |
from collections import OrderedDict |
| 2 |
|
| 3 |
from django.contrib.gis.geos import Polygon |
| 4 |
from django.core.exceptions import ImproperlyConfigured |
| 5 |
from rest_framework.serializers import ( |
| 6 |
LIST_SERIALIZER_KWARGS, |
| 7 |
ListSerializer, |
| 8 |
ModelSerializer, |
| 9 |
) |
| 10 |
|
| 11 |
from .fields import GeometryField, GeometrySerializerMethodField # noqa |
| 12 |
|
| 13 |
|
| 14 |
class GeoModelSerializer(ModelSerializer): |
| 15 |
""" |
| 16 |
Deprecated, will be removed in django-rest-framework-gis 1.0 |
| 17 |
""" |
| 18 |
|
| 19 |
|
| 20 |
class GeoFeatureModelListSerializer(ListSerializer): |
| 21 |
@property |
| 22 |
def data(self): |
| 23 |
return super(ListSerializer, self).data |
| 24 |
|
| 25 |
def to_representation(self, data): |
| 26 |
""" |
| 27 |
Add GeoJSON compatible formatting to a serialized queryset list |
| 28 |
""" |
| 29 |
return OrderedDict( |
| 30 |
( |
| 31 |
("type", "FeatureCollection"), |
| 32 |
("features", super().to_representation(data)), |
| 33 |
) |
| 34 |
) |
| 35 |
|
| 36 |
|
| 37 |
class GeoFeatureModelSerializer(ModelSerializer): |
| 38 |
""" |
| 39 |
A subclass of ModelSerializer |
| 40 |
that outputs geojson-ready data as |
| 41 |
features and feature collections |
| 42 |
""" |
| 43 |
|
| 44 |
@classmethod |
| 45 |
def many_init(cls, *args, **kwargs): |
| 46 |
child_serializer = cls(*args, **kwargs) |
| 47 |
list_kwargs = {"child": child_serializer} |
| 48 |
list_kwargs.update( |
| 49 |
{ |
| 50 |
key: value |
| 51 |
for key, value in kwargs.items() |
| 52 |
if key in LIST_SERIALIZER_KWARGS |
| 53 |
} |
| 54 |
) |
| 55 |
meta = getattr(cls, "Meta", None) |
| 56 |
list_serializer_class = getattr( |
| 57 |
meta, "list_serializer_class", GeoFeatureModelListSerializer |
| 58 |
) |
| 59 |
return list_serializer_class(*args, **list_kwargs) |
| 60 |
|
| 61 |
def __init__(self, *args, **kwargs): |
| 62 |
super().__init__(*args, **kwargs) |
| 63 |
meta = getattr(self, "Meta") |
| 64 |
default_id_field = None |
| 65 |
primary_key = self.Meta.model._meta.pk.name |
| 66 |
# use primary key as id_field when possible |
| 67 |
if ( |
| 68 |
not hasattr(meta, "fields") |
| 69 |
or meta.fields == "__all__" |
| 70 |
or primary_key in meta.fields |
| 71 |
): |
| 72 |
default_id_field = primary_key |
| 73 |
meta.id_field = getattr(meta, "id_field", default_id_field) |
| 74 |
|
| 75 |
if not hasattr(meta, "geo_field"): |
| 76 |
raise ImproperlyConfigured( |
| 77 |
"You must define a 'geo_field'. " |
| 78 |
"Set it to None if there is no geometry." |
| 79 |
) |
| 80 |
|
| 81 |
def check_excludes(field_name, field_role): |
| 82 |
"""make sure the field is not excluded""" |
| 83 |
if hasattr(meta, "exclude") and field_name in meta.exclude: |
| 84 |
raise ImproperlyConfigured(f"You cannot exclude your '{field_role}'.") |
| 85 |
|
| 86 |
def add_to_fields(field_name): |
| 87 |
"""Make sure the field is included in the fields""" |
| 88 |
if hasattr(meta, "fields") and meta.fields != "__all__": |
| 89 |
if field_name not in meta.fields: |
| 90 |
if type(meta.fields) is tuple: |
| 91 |
additional_fields = (field_name,) |
| 92 |
else: |
| 93 |
additional_fields = [field_name] |
| 94 |
meta.fields += additional_fields |
| 95 |
|
| 96 |
check_excludes(meta.geo_field, "geo_field") |
| 97 |
|
| 98 |
if meta.geo_field is not None: |
| 99 |
add_to_fields(meta.geo_field) |
| 100 |
|
| 101 |
meta.bbox_geo_field = getattr(meta, "bbox_geo_field", None) |
| 102 |
if meta.bbox_geo_field: |
| 103 |
check_excludes(meta.bbox_geo_field, "bbox_geo_field") |
| 104 |
add_to_fields(meta.bbox_geo_field) |
| 105 |
|
| 106 |
meta.auto_bbox = getattr(meta, "auto_bbox", False) |
| 107 |
if meta.bbox_geo_field and meta.auto_bbox: |
| 108 |
raise ImproperlyConfigured( |
| 109 |
"You must eiher define a 'bbox_geo_field' or " |
| 110 |
"'auto_bbox', but you can not set both" |
| 111 |
) |
| 112 |
|
| 113 |
def to_representation(self, instance): |
| 114 |
""" |
| 115 |
Serialize objects -> primitives. |
| 116 |
""" |
| 117 |
# prepare OrderedDict geojson structure |
| 118 |
feature = OrderedDict() |
| 119 |
|
| 120 |
# keep track of the fields being processed |
| 121 |
processed_fields = set() |
| 122 |
|
| 123 |
# optional id attribute |
| 124 |
if self.Meta.id_field: |
| 125 |
field = self.fields[self.Meta.id_field] |
| 126 |
value = field.get_attribute(instance) |
| 127 |
feature["id"] = field.to_representation(value) |
| 128 |
processed_fields.add(self.Meta.id_field) |
| 129 |
|
| 130 |
# required type attribute |
| 131 |
# must be "Feature" according to GeoJSON spec |
| 132 |
feature["type"] = "Feature" |
| 133 |
|
| 134 |
# geometry attribute |
| 135 |
# must be present in output according to GeoJSON spec |
| 136 |
if self.Meta.geo_field: |
| 137 |
field = self.fields[self.Meta.geo_field] |
| 138 |
geo_value = field.get_attribute(instance) |
| 139 |
feature["geometry"] = field.to_representation(geo_value) |
| 140 |
processed_fields.add(self.Meta.geo_field) |
| 141 |
else: |
| 142 |
feature["geometry"] = None |
| 143 |
|
| 144 |
# Bounding Box |
| 145 |
# if auto_bbox feature is enabled |
| 146 |
# bbox will be determined automatically automatically |
| 147 |
if self.Meta.auto_bbox and geo_value: |
| 148 |
feature["bbox"] = geo_value.extent |
| 149 |
# otherwise it can be determined via another field |
| 150 |
elif self.Meta.bbox_geo_field: |
| 151 |
field = self.fields[self.Meta.bbox_geo_field] |
| 152 |
value = field.get_attribute(instance) |
| 153 |
feature["bbox"] = value.extent if hasattr(value, "extent") else None |
| 154 |
processed_fields.add(self.Meta.bbox_geo_field) |
| 155 |
|
| 156 |
# the list of fields that will be processed by get_properties |
| 157 |
# we will remove fields that have been already processed |
| 158 |
# to increase performance on large numbers |
| 159 |
fields = [ |
| 160 |
field_value |
| 161 |
for field_key, field_value in self.fields.items() |
| 162 |
if field_key not in processed_fields |
| 163 |
] |
| 164 |
|
| 165 |
# GeoJSON properties |
| 166 |
feature["properties"] = self.get_properties(instance, fields) |
| 167 |
|
| 168 |
return feature |
| 169 |
|
| 170 |
def get_properties(self, instance, fields): |
| 171 |
""" |
| 172 |
Get the feature metadata which will be used for the GeoJSON |
| 173 |
"properties" key. |
| 174 |
|
| 175 |
By default it returns all serializer fields excluding those used for |
| 176 |
the ID, the geometry and the bounding box. |
| 177 |
|
| 178 |
:param instance: The current Django model instance |
| 179 |
:param fields: The list of fields to process (fields already processed have been removed) |
| 180 |
:return: OrderedDict containing the properties of the current feature |
| 181 |
:rtype: OrderedDict |
| 182 |
""" |
| 183 |
properties = OrderedDict() |
| 184 |
|
| 185 |
for field in fields: |
| 186 |
if field.write_only: |
| 187 |
continue |
| 188 |
value = field.get_attribute(instance) |
| 189 |
representation = None |
| 190 |
if value is not None: |
| 191 |
representation = field.to_representation(value) |
| 192 |
properties[field.field_name] = representation |
| 193 |
|
| 194 |
return properties |
| 195 |
|
| 196 |
def to_internal_value(self, data): |
| 197 |
""" |
| 198 |
Override the parent method to first remove the GeoJSON formatting |
| 199 |
""" |
| 200 |
if "properties" in data: |
| 201 |
data = self.unformat_geojson(data) |
| 202 |
return super().to_internal_value(data) |
| 203 |
|
| 204 |
def unformat_geojson(self, feature): |
| 205 |
""" |
| 206 |
This function should return a dictionary containing keys which maps |
| 207 |
to serializer fields. |
| 208 |
|
| 209 |
Remember that GeoJSON contains a key "properties" which contains the |
| 210 |
feature metadata. This should be flattened to make sure this |
| 211 |
metadata is stored in the right serializer fields. |
| 212 |
|
| 213 |
:param feature: The dictionary containing the feature data directly |
| 214 |
from the GeoJSON data. |
| 215 |
:return: A new dictionary which maps the GeoJSON values to |
| 216 |
serializer fields |
| 217 |
""" |
| 218 |
attrs = feature["properties"] |
| 219 |
|
| 220 |
if "geometry" in feature and self.Meta.geo_field: |
| 221 |
attrs[self.Meta.geo_field] = feature["geometry"] |
| 222 |
|
| 223 |
if self.Meta.id_field and "id" in feature: |
| 224 |
attrs[self.Meta.id_field] = feature["id"] |
| 225 |
|
| 226 |
if self.Meta.bbox_geo_field and "bbox" in feature: |
| 227 |
attrs[self.Meta.bbox_geo_field] = Polygon.from_bbox(feature["bbox"]) |
| 228 |
|
| 229 |
return attrs |