I'm using Django 1.8, with GeoDjango and PostGIS. I am using HttpResponse
to return some GeoJSON:
from django.http import HttpResponse, JsonResponse
code = request.GET.get('q', '')
results = PCT.objects.filter(Q(code__startswith=code) |
Q(name__icontains=code))
results = results.filter(org_type='CCG')
for result in results:
print result.code
geo_field = 'boundary'
fields = ('name', 'code', 'ons_code', 'org_type', 'boundary', )
return HttpResponse(serialize('geojson', results,
geometry_field=geo_field, fields=fields),
content_type='application/json')
In the console this prints a code
field just fine:
99N
But the GeoJSON returned does not have a properties.code
field. It has a properties.name
, properties.org_type
and properties.ons_code
field though.
Why is this? Is code
a reserved name perhaps? If so, how can I fix this?
I've had a quick look at the GeoJSON spec and it would appear that it only goes so far as to say that the properties field is a JSON object in its own right, so I think you're in the letter of the current specification if you want it in that part of the JSON dump. That said, this spec is still in draft form and so subject to change (and may yet place extra constraints on this field). Assuming that you can live with that, we can continue...
The code that handles this is in the geojson serializer. This currently will only create data for the geometry, type and properties fields in
get_dump_object()
. But you'll note that the properties field renders whatever is inself._current
. That field is actually built up (by the parent classes' methods) as the serializer iterates over the rest of the fields in the object.By the time
get_dump_object()
is called, self._current should contain all the other serializable fields in the object. As you can see in the base serializer class, fields will only be serialized if they are constructed withserialize=True
and the field is in the list of specified fields you passed in toserialize()
(or you didn't specify a filter so you're going to get everything). I would therefore guess that yourcode
field has been declared as not serializable, or it has an unexpected internal name that doesn't match your filter.To try to fix it, I would have a look at your declaration of the
code
field in your Model for a bad serialize parameter, then just try serializing without any field list at all. Hopefully one of those gets your missing field into the JSON.