[Django]-GeoDjango serialize GeoJSON skipping 'id' field

6๐Ÿ‘

โœ…

As far as the output must be compatible with the specs, the stock serializer omits unsupported fields. However, you could craft your own serializer:

# yourapp/geojson_serializer.py
from django.contrib.gis.serializers import Serializer as GeoJSONSerializer

class Serializer(GeoJSONSerializer):
    def get_dump_object(self, obj):
        data = super(Serializer, self).get_dump_object(obj)
        # Extend to your taste
        data.update(id=obj.pk)
        return data

Enable your new serializer in settings.py:

SERIALIZATION_MODULES = {
        "custom_geojson": "yourapp.geojson_serializer",
}

And then use it in your code:

from django.core import serializers
data = serializers.serialize('custom_geojson', some_model)
๐Ÿ‘คAlex Morozov

2๐Ÿ‘

I was able to solve this as well by using the input from @jayuu . For new readers
interested in this issue I post the complete solution:

#myapp/geojson_serializer.py
from django.core import serializers

GeoJSONSerializer = serializers.get_serializer("geojson")

class Serializer(GeoJSONSerializer):
    def get_dump_object(self, obj):
        data = super(Serializer, self).get_dump_object(obj)
        # Extend to your taste
        data.update(id=obj.pk)
        return data

Then, to use it in my views I just imported the function because I had no interest in registering my serializer

#myapp/views.py
from .geojson_serializer import Serializer

def MapDataView(request):
    geojson_serializer = Serializer()
    geojson_serializer.serialize(some_queryset)
    data = geojson_serializer.getvalue()
    return HttpResponse(data, content_type='json')

And there you have it.

1๐Ÿ‘

One way I solved this was asking it to serialize the โ€œpkโ€ field, which worked as expected.

gqs_serialized = serialize('geojson', gqs, fields=('pk', ))
๐Ÿ‘คChris Ridenour

Leave a comment