django-geojson icon indicating copy to clipboard operation
django-geojson copied to clipboard

Generate FeatureCollection GeoJSON from queryset in the database

Open bahoo opened this issue 5 years ago • 0 comments

I've long wanted to generate GeoJSON directly in the database (i.e. Postgres/PostGIS) since it has JSON and GeoJSON capabilities, and probably has some performance benefits over serialization / pulling everything into memory in Python. This weekend I finally assembled it:

https://gist.github.com/bahoo/fca19de157fde5bb34b30dea8f1352d8

>>> from expressions import GeoJSON
>>> geojson = Geo.objects.filter(**kwargs).aggregate(GeoJSON(geom_field='geom', fields=['name', 'code']))['geojson']
{'type': 'FeatureCollection', 'features': [{'type': 'Feature', 'geometry': {'type': 'MultiPolygon', 'coordinates': [ ... ]

It uses many functions that aren't in core Django yet, so it might be too Postgres-specific to merge into the library yet, but if it helps others trying to do something similar, here you go! Or if anyone thinks it's worth incorporating, I'm happy to put a PR together.

bahoo avatar Oct 17 '20 18:10 bahoo