GeoJSON Serializer

GeoDjango provides a specific serializer for the GeoJSON format. See 序列化 Django 对象 for more information on serialization.

The geojson serializer is not meant for round-tripping data, as it has no deserializer equivalent. For example, you cannot use loaddata to reload the output produced by this serializer. If you plan to reload the outputted data, use the plain json serializer instead.

In addition to the options of the json serializer, the geojson serializer accepts the following additional option when it is called by serializers.serialize():

  • geometry_field: A string containing the name of a geometry field to use for the geometry key of the GeoJSON feature. This is only needed when you have a model with more than one geometry field and you don’t want to use the first defined geometry field (by default, the first geometry field is picked).
  • srid: The SRID to use for the geometry content. Defaults to 4326 (WGS 84).

The fields option can be used to limit fields that will be present in the properties key, as it works with all other serializers.

举例:

  1. from django.core.serializers import serialize
  2. from my_app.models import City
  3. serialize('geojson', City.objects.all(),
  4. geometry_field='point',
  5. fields=('name',))

将会输出:

  1. {
  2. 'type': 'FeatureCollection',
  3. 'crs': {
  4. 'type': 'name',
  5. 'properties': {'name': 'EPSG:4326'}
  6. },
  7. 'features': [
  8. {
  9. 'type': 'Feature',
  10. 'geometry': {
  11. 'type': 'Point',
  12. 'coordinates': [-87.650175, 41.850385]
  13. },
  14. 'properties': {
  15. 'name': 'Chicago'
  16. }
  17. }
  18. ]
  19. }

When the fields parameter is not specified, the geojson serializer adds a pk key to the properties dictionary with the primary key of the object as the value.