对django graphql的geojson支持
django-graphql-geojson的Python项目详细描述
依赖关系
- python≥3.4
- django≥1.11
安装
从pypi安装最后一个稳定版本。
pip install django-graphql-geojson
geojsontype
GeoJSONType是DjangoObjectType的一个子类,它以geojson的格式提供graphql字段。
只需定义一个Meta.geojson_field来表示为Geometry类型。
models.py
fromdjango.contrib.gis.dbimportmodelsclassPlace(models.Model):name=models.CharField(max_length=255)location=models.PointField()
schema.py
importgrapheneimportgraphql_geojsonclassPlaceType(graphql_geojson.GeoJSONType):classMeta:model=models.Placegeojson_field='location'classQuery(graphene.ObjectType):places=graphene.List(PlaceType)schema=graphene.Schema(query=Query)
查询
query { places { id type geometry { type coordinates } bbox properties { name } } }
几何类型
Geometry是表示GEOS geometry object的特殊graphql类型。
schema.py
importgrapheneimportgraphql_geojsonclassCreatePlace(graphene.Mutation):place=graphene.Field(types.PlaceType)classArguments:name=graphene.String(required=True)location=graphql_geojson.Geometry(required=True)@classmethoddefmutate(cls,root,info,**args):place=models.Place.objects.create(**args)returncls(place=place)
突变
mutation CreatePlace($name: String!, $location: Geometry!) { createPlace(name: $name, location: $location) { place { id } } }
Geometry类型可以通过几种方式初始化:
- 知名文本(wkt):
"POINT(5 23)"
- 十六进制(十六进制):
"010100000000000000000014400000000000003740"
- GeoJSON:
{"type":"Point","coordinates":[5,23]}
geometryFilterset
django graphql geojson为spatial lookups提供了一个自定义过滤器集。
Meta.fields选项与model结合,自动生成过滤器。
filters.py
fromgraphql_geojson.filtersimportGeometryFilterSetclassPlaceFilter(GeometryFilterSet):classMeta:model=models.Placefields={'name':['exact'],'location':['exact','intersects','distance_lte'],}
schema.py
importgrapheneimportgraphql_geojsonfromgrapheneimportrelayfromgraphene_django.filterimportDjangoFilterConnectionFieldclassPlaceNode(graphql_geojson.GeoJSONType):classMeta:model=Placeinterfaces=[relay.Node]geojson_field='location'classQuery(graphene.ObjectType):places=DjangoFilterConnectionField(PlaceNode,filterset_class=PlaceFilter)
查询
query Places($geometry: Geometry!){ places(location_Intersects: $geometry) { edges { node { id } } } }
Distance lookups接受一个Distance参数,包含:
- 所需的unit attribute名称
- 距离值
- 从
query Places( $unit: DistanceUnitEnum!, $value: Float!, $geometry: Geometry!) { places(location_DistanceLte: { unit: $unit, value: $value, geometry: $geometry }) { edges { node { id } } } }