4
votes

Hello friends of GeoDjango and the GeoJSON serlizer. I was following the official GeoDjango Tutorial: https://docs.djangoproject.com/en/1.8/ref/contrib/gis/tutorial/

So in the end I have a PostgreSQL + PostGIS database full of countries of, their name, their iso3 code and so on. And especially their geometry in mpoly as MultiPolygon (stored in wkb). I want to retrieve the contries from the database using GeoDjango. I am truggling with that.

I can retrieve the properties of one object one after the other:

from django.http import HttpResponse
from django.shortcuts import render
from django.core.serializers import serialize
from AppName.models import WorldBorder

[...]

WorldBorder.objects.filter(name='Germany')[0].name           # "Germany"
WorldBorder.objects.filter(name='Germany')[0].iso3           # "DEU"
WorldBorder.objects.filter(name='Germany')[0].mpoly.geojson  # long & correct output

So the data is correctly stored in the database and I can retrieve the objects properties. Now I want to get a full geojson file for the country. Django has created the GeoJSON serializer for that: https://docs.djangoproject.com/en/1.8/ref/contrib/gis/serializers/

If I use it in the described way:

serialize('geojson',
  WorldBorder.objects.filter(name='Germany'),
  geometry_field='mpoly',
  fields=('name',)
)

I get this output:

u'{"type": "FeatureCollection", "crs":{"type": "name", "properties": {"name": "EPSG:4326"}},
    "features": [{"geometry": null,"type": "Feature",
    "properties":{"name": "Germany" }}]}'

what is driving me crazy is "geometry": null

So it serializes everything, but not the geometry. Why is that? What am I doing wrong? And especially? How do I get the geometry out of my PostGIS database in GeoJSON format using GeoDjango? Any help is appreciated.

Thank you :)

2
Running into this same issue, did you solve it? - artsim

2 Answers

1
votes

In case anyone else runs into this issue:

It seems the problem is in Django 1.8, geometry has to be passed in the fields for it be serialized.

More here https://code.djangoproject.com/ticket/26138

0
votes

If anybody is still interested in the answer. After a Django update I could fix it by using the normal serializer from the django packages.

from django.core.serializers import serialize

and then serialized using the 'geojson' option:

serialize('geojson', 
  WorldBorder.objects.filter(name='Germany'),
  geometry_field='geom',
  fields=('id', 'name', 'other_properties_you_want')

and it worked like a charm! Except for the fact that the id did not get serialized.