Skip to content

Add support for GeometryCollection fields #138

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 17, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions requirements-test.txt
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
six
psycopg2
djangorestframework>=3.3
coverage==3.7.1 # rq.filter: >=3,<4
Expand Down
1 change: 1 addition & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
six
djangorestframework>=3.3,<3.7
23 changes: 15 additions & 8 deletions rest_framework_gis/fields.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import six # TODO Remove this along with GeoJsonDict when support for python 2.6/2.7 is dropped.
import json
from collections import OrderedDict

Expand Down Expand Up @@ -25,10 +26,7 @@ def to_representation(self, value):
if isinstance(value, dict) or value is None:
return value
# we expect value to be a GEOSGeometry instance
return GeoJsonDict((
('type', value.geom_type),
('coordinates', value.coords),
))
return GeoJsonDict(value.geojson)

def to_internal_value(self, value):
if value == '' or value is None:
Expand All @@ -54,10 +52,7 @@ def to_representation(self, value):
value = super(GeometrySerializerMethodField, self).to_representation(value)
if value is not None:
# we expect value to be a GEOSGeometry instance
return GeoJsonDict((
('type', value.geom_type),
('coordinates', value.coords),
))
return GeoJsonDict(value.geojson)
else:
return None

Expand All @@ -67,6 +62,18 @@ class GeoJsonDict(OrderedDict):
Used for serializing GIS values to GeoJSON values
TODO: remove this when support for python 2.6/2.7 will be dropped
"""
def __init__(self, *args, **kwargs):
"""
If a string is passed attempt to pass it through json.loads,
because it should be a geojson formatted string.
"""
if args and isinstance(args[0], six.string_types):
try:
geojson = json.loads(args[0])
args = (geojson,)
except ValueError:
pass
super(GeoJsonDict, self).__init__(*args, **kwargs)

def __str__(self):
"""
Expand Down
56 changes: 55 additions & 1 deletion tests/django_restframework_gis_tests/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -521,7 +521,7 @@ def test_geometry_serializer_method_field(self):
self.assertEqual(response.status_code, 200)
self.assertEqual(response.data['properties']['name'], 'hidden geometry')
self.assertEqual(response.data['geometry']['type'], 'Point')
self.assertEqual(response.data['geometry']['coordinates'], (0.0, 0.0))
self.assertEqual(response.data['geometry']['coordinates'], [0.0, 0.0])

def test_geometry_serializer_method_field_none(self):
location = Location.objects.create(name='None value', geometry='POINT (135.0 45.0)')
Expand Down Expand Up @@ -584,3 +584,57 @@ def test_pickle(self):
pickled = pickle.dumps(geojsondict)
restored = pickle.loads(pickled)
self.assertEqual(restored, geojsondict)

def test_geometrycollection_geojson(self):
""" test geometry collection geojson behaviour """
location = Location.objects.create(name='geometry collection geojson test',
geometry='GEOMETRYCOLLECTION ('
'POINT (135.0 45.0),'
'LINESTRING (135.0 45.0,140.0 50.0,145.0 55.0),'
'POLYGON ((135.0 45.0,140.0 50.0,145.0 55.0,135.0 45.0)))')
url = reverse('api_geojson_location_details', args=[location.id])
expected = {
'id': location.id,
'type': 'Feature',
'properties': {
'details': "http://testserver/geojson/%s/" % location.id,
'name': 'geometry collection geojson test',
'fancy_name': 'Kool geometry collection geojson test',
'timestamp': None,
'slug': 'geometry-collection-geojson-test',
},
'geometry': {
'type': 'GeometryCollection',
'geometries': [
{
'type': 'Point',
'coordinates': [135.0, 45.0]
},
{
'type': 'LineString',
'coordinates': [
[135.0, 45.0],
[140.0, 50.0],
[145.0, 55.0]
]
},
{
'type': 'Polygon',
'coordinates': [
[
[135.0, 45.0],
[140.0, 50.0],
[145.0, 55.0],
[135.0, 45.0],
]
]
},
],
}
}
response = self.client.get(url)
if sys.version_info > (3, 0, 0):
self.assertCountEqual(json.dumps(response.data), json.dumps(expected))
else:
self.assertItemsEqual(json.dumps(response.data), json.dumps(expected))
self.assertContains(response, "Kool geometry collection geojson test")