通过 Geodjango 中的几何交集关联两个模型

Relate two models by geometry intersection in Geodjango

在 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()

我想查询 returns 位于说英语的国家/地区的所有房屋。
Country 和 House 之间的关系应该通过 House.locationCountry.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)

另一种方法是根据您的需要在此处修改我的回答: