在 GeoDjango 中有两个包含几何字段的模型:
from django.contrib.gis.db import models
class Country(models.Model):
territory = models.MultiPolygonField()
language = models.CharField(max_length=2)
class House(models.Model):
location = models.PointField()
我想查询返回位于说英语的国家/地区的所有房屋。
Country 和 House 之间的关系应该通过将 House.location
与 Country.territory
相交来完成。
如何使用 GeoDjango 的 ORM 实现此目的?
最佳答案
一个有用且相当优化的解决方案是将英语国家的多边形组合成一个 multipolygon (由至少 2 个明确定义的多边形生成的区域)。然后过滤哪些点与该区域相交。
为此,我们将使用 GeoDjango 的 Union
:
Returns a GEOSGeometry object comprising the union of every geometry in the queryset. Please note that use of Union is processor intensive and may take a significant amount of time on large querysets
在 Subquery
中:
Houses.objects.filter(
location__intersects=Subquery(
Country.objects.filter(language='English')
.aggregate(area=Union('territory'))['area']
)
)
或者我们可以避免子查询(对于 Django 版本 < 1.11):
engish_speaking_area = Country.objects.filter(language='English')
.aggregate(area=Union('territory'))['area']
Houses.objects.filter(location__intersects=english_speaking_area)
另一种方法是在这里修改我的答案:GeoDjango query: all point that are contained into a multi polygon根据您的需要。
关于python - 通过 Geodjango 中的几何交集关联两个模型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51257143/