| 1 |
django-rest-framework-gis |
| 2 |
========================= |
| 3 |
|
| 4 |
|Build Status| |Coverage Status| |Requirements Status| |PyPI version| |PyPI downloads| |Black| |
| 5 |
|
| 6 |
Geographic add-ons for Django Rest Framework. |
| 7 |
|
| 8 |
- `Discussions <https://github.com/openwisp/django-rest-framework-gis/discussions>`__ |
| 9 |
- `Mailing List <http://bit.ly/1M4sLTp>`__ |
| 10 |
|
| 11 |
Install last stable version from pypi |
| 12 |
------------------------------------- |
| 13 |
|
| 14 |
.. code-block:: bash |
| 15 |
|
| 16 |
pip install djangorestframework-gis |
| 17 |
|
| 18 |
Install development version |
| 19 |
--------------------------- |
| 20 |
|
| 21 |
.. code-block:: bash |
| 22 |
|
| 23 |
pip install https://github.com/openwisp/django-rest-framework-gis/tarball/master |
| 24 |
|
| 25 |
Setup |
| 26 |
----- |
| 27 |
|
| 28 |
Add ``rest_framework_gis`` in ``settings.INSTALLED_APPS``, after ``rest_framework``: |
| 29 |
|
| 30 |
.. code-block:: python |
| 31 |
|
| 32 |
INSTALLED_APPS = [ |
| 33 |
# ... |
| 34 |
'rest_framework', |
| 35 |
'rest_framework_gis', |
| 36 |
# ... |
| 37 |
] |
| 38 |
|
| 39 |
Compatibility with DRF, Django and Python |
| 40 |
----------------------------------------- |
| 41 |
|
| 42 |
======================== ============================ ==================== ================================== |
| 43 |
DRF-gis version DRF version Django version Python version |
| 44 |
**1.3.x** **3.12** up to **3.18** **4.2 to 6.1** **3.10** to **3.13** |
| 45 |
**1.2.x** **3.12** up to **3.17** **4.2 to 6.0** **3.9** to **3.13** |
| 46 |
**1.1.x** **3.12** up to **3.15** **3.2, 4.2 to 5.1** **3.8** to **3.12** |
| 47 |
**1.0.x** **3.10** up to **3.13** **2.2 to 4.0** **3.6** to **3.9** |
| 48 |
**0.18.x** **3.10** up to **3.13** **2.2 to 4.0** **3.6** to **3.9** |
| 49 |
**0.17.x** **3.10** up to **3.12** **2.2 to 3.1** **3.6** to **3.8** |
| 50 |
**0.16.x** **3.10** **2.2 to 3.1** **3.6** to **3.8** |
| 51 |
**0.15.x** **3.10** **1.11, 2.2 to 3.0** **3.5** to **3.8** |
| 52 |
**0.14.x** **3.3** to **3.9** **1.11** to **2.1** **3.4** to **3.7** |
| 53 |
**0.13.x** **3.3** to **3.8** **1.11** to **2.0** **2.7** to **3.6** |
| 54 |
**0.12.x** **3.1** to **3.7** **1.11** to **2.0** **2.7** to **3.6** |
| 55 |
**0.11.x** **3.1** to **3.6** **1.7** to **1.11** **2.7** to **3.6** |
| 56 |
**0.10.x** **3.1** to **3.3** **1.7** to **1.9** **2.7** to **3.5** |
| 57 |
**0.9.6** **3.1** to **3.2** **1.5** to **1.8** **2.6** to **3.5** |
| 58 |
**0.9.5** **3.1** to **3.2** **1.5** to **1.8** **2.6** to **3.4** |
| 59 |
**0.9.4** **3.1** to **3.2** **1.5** to **1.8** **2.6** to **3.4** |
| 60 |
**0.9.3** **3.1** **1.5** to **1.8** **2.6** to **3.4** |
| 61 |
**0.9.2** **3.1** **1.5** to **1.8** **2.6** to **3.4** |
| 62 |
**0.9.1** **3.1** **1.5** to **1.8** **2.6** to **3.4** |
| 63 |
**0.9** **3.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** |
| 64 |
**0.9** **3.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** |
| 65 |
**0.9** **3.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** |
| 66 |
**0.8.2** **3.0.4** to **3.1.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** |
| 67 |
**0.8.1** **3.0.4** to **3.1.1** **1.5** to **1.8** **2.6**, **2.7**, **3.3**, **3.4** |
| 68 |
**0.8** **3.0.4** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** |
| 69 |
**0.7** **2.4.3** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** |
| 70 |
**0.6** **2.4.3** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** |
| 71 |
**0.5** from **2.3.14** to **2.4.2** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** |
| 72 |
**0.4** from **2.3.14** to **2.4.2** **1.5** to **1.7** **2.6**, **2.7**, **3.3**, **3.4** |
| 73 |
**0.3** from **2.3.14** to **2.4.2** **1.5**, **1.6** **2.6**, **2.7** |
| 74 |
**0.2** from **2.2.2** to **2.3.13** **1.5**, **1.6** **2.6**, **2.7** |
| 75 |
======================== ============================ ==================== ================================== |
| 76 |
|
| 77 |
Fields |
| 78 |
------ |
| 79 |
|
| 80 |
GeometryField |
| 81 |
~~~~~~~~~~~~~ |
| 82 |
|
| 83 |
Provides a ``GeometryField``, which is a subclass of Django Rest Framework |
| 84 |
(from now on **DRF**) ``WritableField``. This field handles GeoDjango |
| 85 |
geometry fields, providing custom ``to_native`` and ``from_native`` |
| 86 |
methods for GeoJSON input/output. |
| 87 |
|
| 88 |
This field takes four optional arguments: |
| 89 |
|
| 90 |
- ``precision``: Passes coordinates through Python's builtin ``round()`` function (`docs |
| 91 |
<https://docs.python.org/3/library/functions.html#round>`_), rounding values to |
| 92 |
the provided level of precision. E.g. A Point with lat/lng of |
| 93 |
``[51.0486, -114.0708]`` passed through a ``GeometryField(precision=2)`` |
| 94 |
would return a Point with a lat/lng of ``[51.05, -114.07]``. |
| 95 |
- ``remove_duplicates``: Remove sequential duplicate coordinates from line and |
| 96 |
polygon geometries. This is particularly useful when used with the ``precision`` |
| 97 |
argument, as the likelihood of duplicate coordinates increase as precision of |
| 98 |
coordinates are reduced. |
| 99 |
- ``auto_bbox``: If ``True``, the GeoJSON object will include |
| 100 |
a `bounding box <https://datatracker.ietf.org/doc/html/rfc7946#section-5>`_, |
| 101 |
which is the smallest possible rectangle enclosing the geometry. |
| 102 |
- ``transform`` (defaults to ``None``): Can be set to any value that is accepted by |
| 103 |
|GEOSGeometry.transform|_. Set to `4326` if your input geometries are in another |
| 104 |
projection and you want to produce output according to the `GeoJSON standard |
| 105 |
<https://datatracker.ietf.org/doc/html/rfc7946#section-4>`_. If ``None`` (or the |
| 106 |
input geometries do not have a SRID), the output coordinates will not be |
| 107 |
transformed. |
| 108 |
|
| 109 |
.. |GEOSGeometry.transform| replace:: ``GEOSGeometry.transform`` |
| 110 |
.. _GEOSGeometry.transform: https://example.org |
| 111 |
|
| 112 |
**Note:** While ``precision`` and ``remove_duplicates`` are designed to reduce the |
| 113 |
byte size of the API response, they will also increase the processing time |
| 114 |
required to render the response. This will likely be negligible for small GeoJSON |
| 115 |
responses but may become an issue for large responses. |
| 116 |
|
| 117 |
**New in 0.9.3:** there is no need to define this field explicitly in your serializer, |
| 118 |
it's mapped automatically during initialization in ``rest_framework_gis.apps.AppConfig.ready()``. |
| 119 |
|
| 120 |
GeometrySerializerMethodField |
| 121 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 122 |
|
| 123 |
Provides a ``GeometrySerializerMethodField``, which is a subclass of DRF |
| 124 |
``SerializerMethodField`` and handles values which are computed with a serializer |
| 125 |
method and are used as a ``geo_field``. `See example below <https://github.com/openwisp/django-rest-framework-gis#using-geometryserializermethodfield-as-geo_field>`__. |
| 126 |
|
| 127 |
Serializers |
| 128 |
----------- |
| 129 |
|
| 130 |
GeoModelSerializer (DEPRECATED) |
| 131 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 132 |
|
| 133 |
**Deprecated, will be removed in 1.0**: Using this serializer is not needed anymore since 0.9.3, if you add |
| 134 |
``rest_framework_gis`` in ``settings.INSTALLED_APPS`` the serialization will work out of the box with DRF. |
| 135 |
Refer `Issue #156 <https://github.com/openwisp/django-rest-framework-gis#using-geometryserializermethodfield-as-geo_field>`__. |
| 136 |
|
| 137 |
Provides a ``GeoModelSerializer``, which is a subclass of DRF |
| 138 |
``ModelSerializer``. This serializer updates the field\_mapping |
| 139 |
dictionary to include field mapping of GeoDjango geometry fields to the |
| 140 |
above ``GeometryField``. |
| 141 |
|
| 142 |
For example, the following model: |
| 143 |
|
| 144 |
.. code-block:: python |
| 145 |
|
| 146 |
class Location(models.Model): |
| 147 |
""" |
| 148 |
A model which holds information about a particular location |
| 149 |
""" |
| 150 |
address = models.CharField(max_length=255) |
| 151 |
city = models.CharField(max_length=100) |
| 152 |
state = models.CharField(max_length=100) |
| 153 |
point = models.PointField() |
| 154 |
|
| 155 |
By default, the DRF ModelSerializer **ver < 0.9.3** will output: |
| 156 |
|
| 157 |
.. code-block:: javascript |
| 158 |
|
| 159 |
{ |
| 160 |
"id": 1, |
| 161 |
"address": "742 Evergreen Terrace", |
| 162 |
"city": "Springfield", |
| 163 |
"state": "Oregon", |
| 164 |
"point": "POINT(-123.0208 44.0464)" |
| 165 |
} |
| 166 |
|
| 167 |
In contrast, the ``GeoModelSerializer`` will output: |
| 168 |
|
| 169 |
.. code-block:: javascript |
| 170 |
|
| 171 |
{ |
| 172 |
"id": 1, |
| 173 |
"address": "742 Evergreen Terrace", |
| 174 |
"city": "Springfield", |
| 175 |
"state": "Oregon", |
| 176 |
"point": { |
| 177 |
"type": "Point", |
| 178 |
"coordinates": [-123.0208, 44.0464], |
| 179 |
} |
| 180 |
} |
| 181 |
|
| 182 |
**Note:** For ``ver>=0.9.3``: The DRF model serializer will give the same output as above, if; |
| 183 |
|
| 184 |
- ``rest_framework_gis`` is set in ``settings.INSTALLED_APPS`` or |
| 185 |
- the field in the serializer is set explicitly as ``GeometryField``. |
| 186 |
|
| 187 |
GeoFeatureModelSerializer |
| 188 |
~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 189 |
|
| 190 |
``GeoFeatureModelSerializer`` is a subclass of ``rest_framework.ModelSerializer`` |
| 191 |
which will output data in a format that is **GeoJSON** compatible. Using |
| 192 |
the above example, the ``GeoFeatureModelSerializer`` will output: |
| 193 |
|
| 194 |
.. code-block:: javascript |
| 195 |
|
| 196 |
{ |
| 197 |
"id": 1, |
| 198 |
"type": "Feature", |
| 199 |
"geometry": { |
| 200 |
"type": "Point", |
| 201 |
"coordinates": [-123.0208, 44.0464], |
| 202 |
}, |
| 203 |
"properties": { |
| 204 |
"address": "742 Evergreen Terrace", |
| 205 |
"city": "Springfield", |
| 206 |
"state": "Oregon" |
| 207 |
} |
| 208 |
} |
| 209 |
|
| 210 |
If you are serializing an object list, ``GeoFeatureModelSerializer`` |
| 211 |
will create a ``FeatureCollection``: |
| 212 |
|
| 213 |
.. code-block:: javascript |
| 214 |
|
| 215 |
{ |
| 216 |
"type": "FeatureCollection", |
| 217 |
"features": [ |
| 218 |
{ |
| 219 |
"id": 1 |
| 220 |
"type": "Feature", |
| 221 |
"geometry": { |
| 222 |
"type": "Point", |
| 223 |
"coordinates": [-123.0208, 44.0464], |
| 224 |
}, |
| 225 |
"properties": { |
| 226 |
"address": "742 Evergreen Terrace", |
| 227 |
"city": "Springfield", |
| 228 |
"state": "Oregon", |
| 229 |
} |
| 230 |
} |
| 231 |
{ |
| 232 |
"id": 2, |
| 233 |
"type": "Feature", |
| 234 |
"geometry": { |
| 235 |
"type": "Point", |
| 236 |
"coordinates": [-123.0208, 44.0489], |
| 237 |
}, |
| 238 |
"properties": { |
| 239 |
"address": "744 Evergreen Terrace", |
| 240 |
"city": "Springfield", |
| 241 |
"state": "Oregon" |
| 242 |
} |
| 243 |
} |
| 244 |
} |
| 245 |
|
| 246 |
Specifying the geometry field: "geo_field" |
| 247 |
########################################## |
| 248 |
|
| 249 |
``GeoFeatureModelSerializer`` requires you to define a ``geo_field`` |
| 250 |
to be serialized as the "geometry". For example: |
| 251 |
|
| 252 |
.. code-block:: python |
| 253 |
|
| 254 |
from rest_framework_gis.serializers import GeoFeatureModelSerializer |
| 255 |
|
| 256 |
class LocationSerializer(GeoFeatureModelSerializer): |
| 257 |
""" A class to serialize locations as GeoJSON compatible data """ |
| 258 |
|
| 259 |
class Meta: |
| 260 |
model = Location |
| 261 |
geo_field = "point" |
| 262 |
|
| 263 |
# you can also explicitly declare which fields you want to include |
| 264 |
# as with a ModelSerializer. |
| 265 |
fields = ('id', 'address', 'city', 'state') |
| 266 |
|
| 267 |
If your model is geometry-less, you can set ``geo_field`` to ``None`` |
| 268 |
and a null geometry will be produced. |
| 269 |
|
| 270 |
Using GeometrySerializerMethodField as "geo_field" |
| 271 |
################################################## |
| 272 |
|
| 273 |
``geo_field`` may also be an instance of ``GeometrySerializerMethodField``. |
| 274 |
In this case you can compute its value during serialization. For example: |
| 275 |
|
| 276 |
.. code-block:: python |
| 277 |
|
| 278 |
from django.contrib.gis.geos import Point |
| 279 |
from rest_framework_gis.serializers import GeoFeatureModelSerializer, GeometrySerializerMethodField |
| 280 |
|
| 281 |
class LocationSerializer(GeoFeatureModelSerializer): |
| 282 |
""" A class to serialize locations as GeoJSON compatible data """ |
| 283 |
|
| 284 |
# a field which contains a geometry value and can be used as geo_field |
| 285 |
other_point = GeometrySerializerMethodField() |
| 286 |
|
| 287 |
def get_other_point(self, obj): |
| 288 |
return Point(obj.point.lat / 2, obj.point.lon / 2) |
| 289 |
|
| 290 |
class Meta: |
| 291 |
model = Location |
| 292 |
geo_field = 'other_point' |
| 293 |
|
| 294 |
Serializer for ``geo_field`` may also return ``None`` value, which will translate to ``null`` value for geojson ``geometry`` field. |
| 295 |
|
| 296 |
Specifying the ID: "id_field" |
| 297 |
############################# |
| 298 |
|
| 299 |
The primary key of the model (usually the "id" attribute) is |
| 300 |
automatically used as the ``id`` field of each |
| 301 |
`GeoJSON Feature Object <https://tools.ietf.org/html/draft-butler-geojson#section-2.2>`_. |
| 302 |
|
| 303 |
The default behaviour follows the `GeoJSON RFC <https://tools.ietf.org/html/draft-butler-geojson>`_, |
| 304 |
but it can be disabled by setting ``id_field`` to ``False``: |
| 305 |
|
| 306 |
.. code-block:: python |
| 307 |
|
| 308 |
from rest_framework_gis.serializers import GeoFeatureModelSerializer |
| 309 |
|
| 310 |
class LocationSerializer(GeoFeatureModelSerializer): |
| 311 |
|
| 312 |
class Meta: |
| 313 |
model = Location |
| 314 |
geo_field = "point" |
| 315 |
id_field = False |
| 316 |
fields = ('id', 'address', 'city', 'state') |
| 317 |
|
| 318 |
The ``id_field`` can also be set to use some other unique field in your model, eg: ``slug``: |
| 319 |
|
| 320 |
.. code-block:: python |
| 321 |
|
| 322 |
from rest_framework_gis.serializers import GeoFeatureModelSerializer |
| 323 |
|
| 324 |
class LocationSerializer(GeoFeatureModelSerializer): |
| 325 |
|
| 326 |
class Meta: |
| 327 |
model = Location |
| 328 |
geo_field = 'point' |
| 329 |
id_field = 'slug' |
| 330 |
fields = ('slug', 'address', 'city', 'state') |
| 331 |
|
| 332 |
Bounding Box: "auto_bbox" and "bbox_geo_field" |
| 333 |
############################################## |
| 334 |
|
| 335 |
The GeoJSON specification allows a feature to contain a |
| 336 |
`boundingbox of a feature <http://geojson.org/geojson-spec.html#geojson-objects>`__. |
| 337 |
``GeoFeatureModelSerializer`` allows two different ways to fill this property. The first |
| 338 |
is using the ``geo_field`` to calculate the bounding box of a feature. This only allows |
| 339 |
read access for a REST client and can be achieved using ``auto_bbox``. Example: |
| 340 |
|
| 341 |
.. code-block:: python |
| 342 |
|
| 343 |
from rest_framework_gis.serializers import GeoFeatureModelSerializer |
| 344 |
|
| 345 |
class LocationSerializer(GeoFeatureModelSerializer): |
| 346 |
class Meta: |
| 347 |
model = Location |
| 348 |
geo_field = 'geometry' |
| 349 |
auto_bbox = True |
| 350 |
|
| 351 |
|
| 352 |
The second approach uses the ``bbox_geo_field`` to specify an additional |
| 353 |
``GeometryField`` of the model which will be used to calculate the bounding box. This allows |
| 354 |
boundingboxes differ from the exact extent of a features geometry. Additionally this |
| 355 |
enables read and write access for the REST client. Bounding boxes send from the client will |
| 356 |
be saved as Polygons. Example: |
| 357 |
|
| 358 |
.. code-block:: python |
| 359 |
|
| 360 |
from rest_framework_gis.serializers import GeoFeatureModelSerializer |
| 361 |
|
| 362 |
class LocationSerializer(GeoFeatureModelSerializer): |
| 363 |
|
| 364 |
class Meta: |
| 365 |
model = BoxedLocation |
| 366 |
geo_field = 'geometry' |
| 367 |
bbox_geo_field = 'bbox_geometry' |
| 368 |
|
| 369 |
|
| 370 |
Custom GeoJSON properties source |
| 371 |
################################ |
| 372 |
|
| 373 |
In GeoJSON each feature can have a ``properties`` member containing the |
| 374 |
attributes of the feature. By default this field is filled with the |
| 375 |
attributes from your Django model, excluding the id, geometry and bounding |
| 376 |
box fields. It's possible to override this behaviour and implement a custom |
| 377 |
source for the ``properties`` member. |
| 378 |
|
| 379 |
The following example shows how to use a PostgreSQL HStore field as a source for |
| 380 |
the ``properties`` member: |
| 381 |
|
| 382 |
.. code-block:: python |
| 383 |
|
| 384 |
# models.py |
| 385 |
class Link(models.Model): |
| 386 |
""" |
| 387 |
Metadata is stored in a PostgreSQL HStore field, which allows us to |
| 388 |
store arbitrary key-value pairs with a link record. |
| 389 |
""" |
| 390 |
metadata = HStoreField(blank=True, null=True, default=dict) |
| 391 |
geo = models.LineStringField() |
| 392 |
objects = models.GeoManager() |
| 393 |
|
| 394 |
# serializers.py |
| 395 |
class NetworkGeoSerializer(GeoFeatureModelSerializer): |
| 396 |
class Meta: |
| 397 |
model = models.Link |
| 398 |
geo_field = 'geo' |
| 399 |
auto_bbox = True |
| 400 |
|
| 401 |
def get_properties(self, instance, fields): |
| 402 |
# This is a PostgreSQL HStore field, which django maps to a dict |
| 403 |
return instance.metadata |
| 404 |
|
| 405 |
def unformat_geojson(self, feature): |
| 406 |
attrs = { |
| 407 |
self.Meta.geo_field: feature["geometry"], |
| 408 |
"metadata": feature["properties"] |
| 409 |
} |
| 410 |
|
| 411 |
if self.Meta.bbox_geo_field and "bbox" in feature: |
| 412 |
attrs[self.Meta.bbox_geo_field] = Polygon.from_bbox(feature["bbox"]) |
| 413 |
|
| 414 |
return attrs |
| 415 |
|
| 416 |
When the serializer renders GeoJSON, it calls the method |
| 417 |
``get_properties`` for each object in the database. This function |
| 418 |
should return a dictionary containing the attributes for the feature. In the |
| 419 |
case of a HStore field, this function is easily implemented. |
| 420 |
|
| 421 |
The reverse is also required: mapping a GeoJSON formatted structure to |
| 422 |
attributes of your model. This task is done by ``unformat_geojson``. It should |
| 423 |
return a dictionary with your model attributes as keys, and the corresponding |
| 424 |
values retrieved from the GeoJSON feature data. |
| 425 |
|
| 426 |
Pagination |
| 427 |
---------- |
| 428 |
|
| 429 |
We provide a ``GeoJsonPagination`` class. |
| 430 |
|
| 431 |
GeoJsonPagination |
| 432 |
~~~~~~~~~~~~~~~~~ |
| 433 |
|
| 434 |
Based on ``rest_framework.pagination.PageNumberPagination``. |
| 435 |
|
| 436 |
Code example: |
| 437 |
|
| 438 |
.. code-block:: python |
| 439 |
|
| 440 |
from rest_framework_gis.pagination import GeoJsonPagination |
| 441 |
# --- other omitted imports --- # |
| 442 |
|
| 443 |
class GeojsonLocationList(generics.ListCreateAPIView): |
| 444 |
# -- other omitted view attributes --- # |
| 445 |
pagination_class = GeoJsonPagination |
| 446 |
|
| 447 |
Example result response (cut to one element only instead of 10): |
| 448 |
|
| 449 |
.. code-block:: javascript |
| 450 |
|
| 451 |
{ |
| 452 |
"type": "FeatureCollection", |
| 453 |
"count": 25, |
| 454 |
"next": "http://localhost:8000/geojson/?page=2", |
| 455 |
"previous": null, |
| 456 |
"features": [ |
| 457 |
{ |
| 458 |
"type": "Feature", |
| 459 |
"geometry": { |
| 460 |
"type": "Point", |
| 461 |
"coordinates": [ |
| 462 |
42.0, |
| 463 |
50.0 |
| 464 |
] |
| 465 |
}, |
| 466 |
"properties": { |
| 467 |
"name": "test" |
| 468 |
} |
| 469 |
} |
| 470 |
] |
| 471 |
} |
| 472 |
|
| 473 |
|
| 474 |
Filters |
| 475 |
------- |
| 476 |
|
| 477 |
**note**: this feature has been tested up to django-filter 1.0. |
| 478 |
|
| 479 |
We provide a ``GeometryFilter`` field as well as a ``GeoFilterSet`` |
| 480 |
for usage with ``django_filter``. You simply provide, in the query |
| 481 |
string, one of the textual types supported by ``GEOSGeometry``. By |
| 482 |
default, this includes WKT, HEXEWKB, WKB (in a buffer), and GeoJSON. |
| 483 |
|
| 484 |
GeometryFilter |
| 485 |
~~~~~~~~~~~~~~ |
| 486 |
|
| 487 |
.. code-block:: python |
| 488 |
|
| 489 |
from rest_framework_gis.filterset import GeoFilterSet |
| 490 |
from rest_framework_gis.filters import GeometryFilter |
| 491 |
from django_filters import filters |
| 492 |
|
| 493 |
class RegionFilter(GeoFilterSet): |
| 494 |
slug = filters.CharFilter(name='slug', lookup_expr='istartswith') |
| 495 |
contains_geom = GeometryFilter(name='geom', lookup_expr='contains') |
| 496 |
|
| 497 |
class Meta: |
| 498 |
model = Region |
| 499 |
|
| 500 |
We can then filter in the URL, using GeoJSON, and we will perform a |
| 501 |
``__contains`` geometry lookup, e.g. |
| 502 |
``/region/?contains_geom={ "type": "Point", "coordinates": [ -123.26436996459961, 44.564178042345375 ] }``. |
| 503 |
|
| 504 |
GeoFilterSet |
| 505 |
~~~~~~~~~~~~ |
| 506 |
|
| 507 |
The ``GeoFilterSet`` provides a ``django_filter`` compatible |
| 508 |
``FilterSet`` that will automatically create ``GeometryFilters`` for |
| 509 |
``GeometryFields``. |
| 510 |
|
| 511 |
InBBoxFilter |
| 512 |
~~~~~~~~~~~~ |
| 513 |
|
| 514 |
Provides a ``InBBoxFilter``, which is a subclass of DRF |
| 515 |
``BaseFilterBackend``. Filters a queryset to only those instances within |
| 516 |
a certain bounding box. |
| 517 |
|
| 518 |
|
| 519 |
``views.py:`` |
| 520 |
|
| 521 |
.. code-block:: python |
| 522 |
|
| 523 |
from rest_framework_gis.filters import InBBoxFilter |
| 524 |
|
| 525 |
class LocationList(ListAPIView): |
| 526 |
|
| 527 |
queryset = models.Location.objects.all() |
| 528 |
serializer_class = serializers.LocationSerializer |
| 529 |
bbox_filter_field = 'point' |
| 530 |
filter_backends = (InBBoxFilter,) |
| 531 |
bbox_filter_include_overlapping = True # Optional |
| 532 |
|
| 533 |
We can then filter in the URL, using Bounding Box format (min Lon, min |
| 534 |
Lat, max Lon, max Lat), and we can search for instances within the |
| 535 |
bounding box, e.g.: |
| 536 |
``/location/?in_bbox=-90,29,-89,35``. |
| 537 |
|
| 538 |
By default, InBBoxFilter will only return those instances entirely |
| 539 |
within the stated bounding box. To include those instances which overlap |
| 540 |
the bounding box, include ``bbox_filter_include_overlapping = True`` |
| 541 |
in your view. |
| 542 |
|
| 543 |
Note that if you are using other filters, you'll want to include your |
| 544 |
other filter backend in your view. For example: |
| 545 |
|
| 546 |
``filter_backends = (InBBoxFilter, DjangoFilterBackend,)`` |
| 547 |
|
| 548 |
TMSTileFilter |
| 549 |
~~~~~~~~~~~~~ |
| 550 |
|
| 551 |
Provides a ``TMSTileFilter``, which is a subclass of ``InBBoxFilter``. |
| 552 |
Filters a queryset to only those instances within a bounding box defined |
| 553 |
by a `TMS tile <http://wiki.openstreetmap.org/wiki/TMS>`__ address. |
| 554 |
|
| 555 |
``views.py:`` |
| 556 |
|
| 557 |
.. code-block:: python |
| 558 |
|
| 559 |
from rest_framework_gis.filters import TMSTileFilter |
| 560 |
|
| 561 |
class LocationList(ListAPIView): |
| 562 |
|
| 563 |
queryset = models.Location.objects.all() |
| 564 |
serializer_class = serializers.LocationSerializer |
| 565 |
bbox_filter_field = 'point' |
| 566 |
filter_backends = (TMSTileFilter,) |
| 567 |
bbox_filter_include_overlapping = True # Optional |
| 568 |
|
| 569 |
We can then filter in the URL, using TMS tile addresses in the zoom/x/y format, |
| 570 |
eg:. |
| 571 |
``/location/?tile=8/100/200`` |
| 572 |
which is equivalent to filtering on the bbox (-39.37500,-71.07406,-37.96875,-70.61261). |
| 573 |
|
| 574 |
For more information on configuration options see InBBoxFilter. |
| 575 |
|
| 576 |
Note that the tile address start in the upper left, not the lower left origin used by some |
| 577 |
implementations. |
| 578 |
|
| 579 |
DistanceToPointFilter |
| 580 |
~~~~~~~~~~~~~~~~~~~~~ |
| 581 |
|
| 582 |
Provides a ``DistanceToPointFilter``, which is a subclass of DRF |
| 583 |
``BaseFilterBackend``. Filters a queryset to only those instances within |
| 584 |
a certain distance of a given point. |
| 585 |
|
| 586 |
``views.py:`` |
| 587 |
|
| 588 |
.. code-block:: python |
| 589 |
|
| 590 |
from rest_framework_gis.filters import DistanceToPointFilter |
| 591 |
|
| 592 |
class LocationList(ListAPIView): |
| 593 |
|
| 594 |
queryset = models.Location.objects.all() |
| 595 |
serializer_class = serializers.LocationSerializer |
| 596 |
distance_filter_field = 'geometry' |
| 597 |
filter_backends = (DistanceToPointFilter,) |
| 598 |
|
| 599 |
We can then filter in the URL, using a distance and a point in (lon, lat) format. The |
| 600 |
distance can be given in meters or in degrees. |
| 601 |
|
| 602 |
eg:. |
| 603 |
``/location/?dist=4000&point=-122.4862,37.7694&format=json`` |
| 604 |
which is equivalent to filtering within 4000 meters of the point (-122.4862, 37.7694). |
| 605 |
|
| 606 |
By default, DistanceToPointFilter will pass the 'distance' in the URL directly to the database for the search. |
| 607 |
The effect depends on the srid of the database in use. If geo data is indexed in meters (srid 3875, aka 900913), a |
| 608 |
distance in meters can be passed in directly without conversion. For lat-lon databases such as srid 4326, |
| 609 |
which is indexed in degrees, the 'distance' will be interpreted as degrees. Set the flag, 'distance_filter_convert_meters' |
| 610 |
to 'True' in order to convert an input distance in meters to degrees. This conversion is approximate, and the errors |
| 611 |
at latitudes > 60 degrees are > 25%. |
| 612 |
|
| 613 |
DistanceToPointOrderingFilter |
| 614 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 615 |
|
| 616 |
Provides a ``DistanceToPointOrderingFilter``, which is a subclass of ``DistanceToPointFilter``. |
| 617 |
Orders a queryset by distance to a given point, from the nearest to the most distant point. |
| 618 |
|
| 619 |
``views.py:`` |
| 620 |
|
| 621 |
.. code-block:: python |
| 622 |
|
| 623 |
from rest_framework_gis.filters import DistanceToPointOrderingFilter |
| 624 |
|
| 625 |
class LocationList(ListAPIView): |
| 626 |
|
| 627 |
queryset = models.Location.objects.all() |
| 628 |
serializer_class = serializers.LocationSerializer |
| 629 |
distance_ordering_filter_field = 'geometry' |
| 630 |
filter_backends = (DistanceToPointOrderingFilter,) |
| 631 |
|
| 632 |
We can then order the results by passing a point in (lon, lat) format in the URL. |
| 633 |
|
| 634 |
eg:. |
| 635 |
``/location/?point=-122.4862,37.7694&format=json`` |
| 636 |
will order the results by the distance to the point (-122.4862, 37.7694). |
| 637 |
|
| 638 |
We can also reverse the order of the results by passing ``order=desc``: |
| 639 |
``/location/?point=-122.4862,37.7694&order=desc&format=json`` |
| 640 |
|
| 641 |
Schema Generation |
| 642 |
----------------- |
| 643 |
|
| 644 |
Note: Schema generation support is available only for DRF >= 3.12. |
| 645 |
|
| 646 |
Simplest Approach would be, change ``DEFAULT_SCHEMA_CLASS`` to ``rest_framework_gis.schema.GeoFeatureAutoSchema``: |
| 647 |
|
| 648 |
.. code-block:: python |
| 649 |
|
| 650 |
REST_FRAMEWORK = { |
| 651 |
... |
| 652 |
'DEFAULT_SCHEMA_CLASS': 'rest_framework_gis.schema.GeoFeatureAutoSchema', |
| 653 |
... |
| 654 |
} |
| 655 |
|
| 656 |
If you do not want to change default schema generator class: |
| 657 |
|
| 658 |
- You can pass this class as an argument to ``get_schema_view`` function `[Ref] <https://www.django-rest-framework.org/api-guide/schemas/#generating-a-dynamic-schema-with-schemaview>`__. |
| 659 |
- You can pass this class as an argument to the ``generateschema`` command `[Ref] <https://www.django-rest-framework.org/api-guide/schemas/#generating-a-static-schema-with-the-generateschema-management-command>`__. |
| 660 |
|
| 661 |
Running the tests |
| 662 |
----------------- |
| 663 |
|
| 664 |
Required setup |
| 665 |
============== |
| 666 |
|
| 667 |
You need one of the `Spatial Database servers supported by |
| 668 |
GeoDjango <https://docs.djangoproject.com/en/dev/ref/contrib/gis/db-api/#module-django.contrib.gis.db.backends>`__, |
| 669 |
and create a database for the tests. |
| 670 |
|
| 671 |
The following can be used with PostgreSQL: |
| 672 |
|
| 673 |
.. code-block:: bash |
| 674 |
|
| 675 |
createdb django_restframework_gis |
| 676 |
psql -U postgres -d django_restframework_gis -c "CREATE EXTENSION postgis" |
| 677 |
|
| 678 |
You might need to tweak the DB settings according to your DB |
| 679 |
configuration. You can copy the file ``local_settings.example.py`` to |
| 680 |
``local_settings.py`` and change the ``DATABASES`` and/or |
| 681 |
``INSTALLED_APPS`` directives there. |
| 682 |
|
| 683 |
This should allow you to run the tests already. |
| 684 |
|
| 685 |
For reference, the following steps will setup a development environment for |
| 686 |
contributing to the project: |
| 687 |
|
| 688 |
- create a spatial database named "django\_restframework\_gis" |
| 689 |
- create ``local_settings.py``, eg: |
| 690 |
``cp local_settings.example.py local_settings.py`` |
| 691 |
- tweak the ``DATABASES`` configuration directive according to your DB |
| 692 |
settings |
| 693 |
- uncomment ``INSTALLED_APPS`` |
| 694 |
- run ``python manage.py syncdb`` |
| 695 |
- run ``python manage.py collectstatic`` |
| 696 |
- run ``python manage.py runserver`` |
| 697 |
|
| 698 |
Using tox |
| 699 |
========= |
| 700 |
|
| 701 |
The recommended way to run the tests is by using |
| 702 |
`tox <https://tox.readthedocs.io/en/latest/>`__, which can be installed using |
| 703 |
`pip install tox`. |
| 704 |
|
| 705 |
You can use ``tox -l`` to list the available environments, and then e.g. use |
| 706 |
the following to run all tests with Python 3.13 and Django 6.0: |
| 707 |
|
| 708 |
.. code-block:: bash |
| 709 |
|
| 710 |
tox -e py313-django60 |
| 711 |
|
| 712 |
By default Django's test runner is used, but there is a variation of tox's |
| 713 |
envlist to use pytest (using the ``-pytest`` suffix). |
| 714 |
|
| 715 |
You can pass optional arguments to the test runner like this: |
| 716 |
|
| 717 |
.. code-block:: bash |
| 718 |
|
| 719 |
tox -e py38-django42-pytest -- -k test_foo |
| 720 |
|
| 721 |
Running tests manually |
| 722 |
====================== |
| 723 |
|
| 724 |
Please refer to the ``tox.ini`` file for reference/help in case you want to run |
| 725 |
tests manually / without tox. |
| 726 |
|
| 727 |
To run tests in docker use |
| 728 |
|
| 729 |
.. code-block:: bash |
| 730 |
|
| 731 |
docker-compose build |
| 732 |
docker-compose run --rm test |
| 733 |
|
| 734 |
Running QA-checks |
| 735 |
================= |
| 736 |
|
| 737 |
Install the test requirements: |
| 738 |
|
| 739 |
.. code-block:: shell |
| 740 |
|
| 741 |
pip install -r requirements-test.txt |
| 742 |
|
| 743 |
Reformat the code according to |
| 744 |
`our coding style conventions with <https://openwisp.io/docs/developer/contributing.html#coding-style-conventions>`_: |
| 745 |
|
| 746 |
.. code-block:: shell |
| 747 |
|
| 748 |
openwisp-qa-format |
| 749 |
|
| 750 |
Run the QA checks by using |
| 751 |
|
| 752 |
.. code-block:: shell |
| 753 |
|
| 754 |
./run-qa-checks |
| 755 |
|
| 756 |
In docker testing, QA checks are executed automatically. |
| 757 |
|
| 758 |
Contributing |
| 759 |
------------ |
| 760 |
|
| 761 |
1. Announce your intentions in the |
| 762 |
`Github Discussions Forum <https://github.com/openwisp/django-rest-framework-gis/discussions>`__ |
| 763 |
2. Follow the `PEP8 Style Guide for Python |
| 764 |
Code <http://www.python.org/dev/peps/pep-0008/>`__ |
| 765 |
3. Fork this repo |
| 766 |
4. Write code |
| 767 |
5. Write tests for your code |
| 768 |
6. Ensure all tests pass |
| 769 |
7. Ensure test coverage is not under 90% |
| 770 |
8. Document your changes |
| 771 |
9. Send pull request |
| 772 |
|
| 773 |
.. |Build Status| image:: https://github.com/openwisp/django-rest-framework-gis/actions/workflows/ci.yml/badge.svg |
| 774 |
:target: https://github.com/openwisp/django-rest-framework-gis/actions/workflows/ci.yml |
| 775 |
.. |Coverage Status| image:: https://coveralls.io/repos/openwisp/django-rest-framework-gis/badge.svg |
| 776 |
:target: https://coveralls.io/r/openwisp/django-rest-framework-gis |
| 777 |
.. |Requirements Status| image:: https://img.shields.io/librariesio/release/github/openwisp/django-rest-framework-gis |
| 778 |
:target: https://libraries.io/github/openwisp/django-rest-framework-gis#repository_dependencies |
| 779 |
:alt: Dependency monitoring |
| 780 |
.. |PyPI version| image:: https://badge.fury.io/py/djangorestframework-gis.svg |
| 781 |
:target: http://badge.fury.io/py/djangorestframework-gis |
| 782 |
.. |PyPI downloads| image:: https://pepy.tech/badge/djangorestframework-gis/month |
| 783 |
:target: https://pepy.tech/project/djangorestframework-gis |
| 784 |
.. |Black| image:: https://img.shields.io/badge/code%20style-black-000000.svg |
| 785 |
:target: https://pypi.org/project/black/ |