ここのことはなかったことにするかもしれない

仕事がらみの記事を主として扱いますが、あくまで個人ブログです。2013年以前の記事は https://yellow-73.hatenablog.com/ にあります。

GeoDjangoに挑戦中 #4 GeoJSONを吐く

参考URL

https://homata.gitbook.io/geodjango/geodjango/tutorial#geojson-serializer

ビューを登録する

(アプリ名)/urls.py

urlpatterns = [
    ....
    path('geojson/', GeojsonAPIView.as_view(), name='geojson_view'),
    ....
]

(アプリ名)/views.py

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
import traceback
import json
from django.core.serializers import serialize

class GeojsonAPIView(APIView):
    def get(self, request, *args, **keywords):
        try:
            encjson  = serialize(
                'geojson',
                FieldPolygon.objects.all(),
                srid=4326,
                geometry_field='geom',
                fields=('gid', 'name')  
            )
            result   = json.loads(encjson)
            response = Response(result, status=status.HTTP_200_OK)
        except Exception as e:
            traceback.print_exc()
            response = Response({}, status=status.HTTP_404_NOT_FOUND)
        except:
            response = Response({}, status=status.HTTP_404_NOT_FOUND)
        return response
  • fieldsに指定したカラムがプロパティになります。
  • FieldPolygon.object.all()FieldPolygon.object.filter()等をかけられるようです。