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