[英]Intersecting multipolygon layer with polygon in GeoDjango
I have a Region
GeoDjango model (deriving from django.contrib.gis.db.models.Model
), with a geom
field, which is a django.contrib.gis.db.models.MultiPolygonField
.
我想计算这个 model(代表存储在 PostGIS 中的一组多边形区域)与 GeoJSON 多边形“查询”的交集:
from django.contrib.gis.geos import GEOSGeometry
query = GEOSGeometry(
'{"type":"Polygon","coordinates":[[[-80.983786,43.929011],[-80.511513,43.778458],[-80.291852,44.079184],[-80.775108,44.232127],[-80.983786,43.929011]]]}'
)
我尝试了很多事情:
results = Region.objects.all().intersection(query)
或者
from django.contrib.gis.db.models.functions import Intersection
results = Intersection(Region.objects.all(), query)
但似乎我没有正确的方法。
请注意,我不想简单地计算与查询相交的区域子集,而是计算它们的确切交集(换句话说,生成的多边形集应该与查询具有完全相同的形状)。
本质上,我们需要用给定的query
annotate
每个Region
的geom
的intersection
(如果有的话)。 使用 DB 查询执行此操作如下所示:
from django.db.models import F
from django.contrib.gis.db.models.functions import Intersection
from django.contrib.gis.geos import GEOSGeometry
query = GEOSGeometry(
'{"type":"Polygon","coordinates":[[[-80.983786,43.929011],[-80.511513,43.778458],[-80.291852,44.079184],[-80.775108,44.232127],[-80.983786,43.929011]]]}'
)
results = Region.objects.filter(geom__intersects=query).annotate(
intersection_geom=Intersection(F('geom'), query)
)
查询说明:
intersects
空间查找过滤与query
相交的Regions
。F()
表达式访问geom
计算区域的geom
字段和query
的Intersection
的结果(关于F()
用法的说明可以在我的问答示例中找到: 如何在 django 中的 Model 字段之间执行算术运算)annotate
到每个对应的Region
中,作为名为intersection_geom
的字段。 查询执行后, results
将包含与query
几何相交的每个Region
, intersection_geom
字段包含相应相交的确切几何。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.