serializers.txt 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. ======================
  2. ``GeoJSON`` Serializer
  3. ======================
  4. .. module:: django.contrib.gis.serializers.geojson
  5. :synopsis: Serialization of GeoDjango models in the GeoJSON format.
  6. GeoDjango provides a specific serializer for the `GeoJSON`__ format. See
  7. :doc:`/topics/serialization` for more information on serialization.
  8. __ https://geojson.org/
  9. The ``geojson`` serializer is not meant for round-tripping data, as it has no
  10. deserializer equivalent. For example, you cannot use :djadmin:`loaddata` to
  11. reload the output produced by this serializer. If you plan to reload the
  12. outputted data, use the plain :ref:`json serializer <serialization-formats-json>`
  13. instead.
  14. In addition to the options of the ``json`` serializer, the ``geojson``
  15. serializer accepts the following additional option when it is called by
  16. ``serializers.serialize()``:
  17. * ``geometry_field``: A string containing the name of a geometry field to use
  18. for the ``geometry`` key of the GeoJSON feature. This is only needed when you
  19. have a model with more than one geometry field and you don't want to use the
  20. first defined geometry field (by default, the first geometry field is picked).
  21. * ``id_field``: A string containing the name of a field to use for the ``id``
  22. key of the GeoJSON feature. By default, the primary key of objects is used.
  23. * ``srid``: The SRID to use for the ``geometry`` content. Defaults to 4326
  24. (WGS 84).
  25. The :ref:`fields <subset-of-fields>` option can be used to limit fields that
  26. will be present in the ``properties`` key, as it works with all other
  27. serializers.
  28. Example::
  29. from django.core.serializers import serialize
  30. from my_app.models import City
  31. serialize("geojson", City.objects.all(), geometry_field="point", fields=["name"])
  32. Would output::
  33. {
  34. "type": "FeatureCollection",
  35. "crs": {"type": "name", "properties": {"name": "EPSG:4326"}},
  36. "features": [
  37. {
  38. "type": "Feature",
  39. "id": 1,
  40. "geometry": {"type": "Point", "coordinates": [-87.650175, 41.850385]},
  41. "properties": {"name": "Chicago"},
  42. }
  43. ],
  44. }
  45. When the ``fields`` parameter is not specified, the ``geojson`` serializer adds
  46. a ``pk`` key to the ``properties`` dictionary with the primary key of the
  47. object as the value.