如何在 GeoDjango 中使用子查询获取相交几何图形?

How to get intersecting geometries with subquery in GeoDjango?

我正在尝试从 table 中获取所有记录,其几何与来自相同 table 的缓冲几何相交,这是我通过子查询获得的。

我的工作原理 SQL 语句是:

SELECT id FROM table 
WHERE ST_INTERSECTS(geom, (
    SELECT ST_BUFFER(geom, 10) FROM table WHERE id = 1)
);

如何使用 GeoDjango 实现此目的?

编辑:

得到它与以下工作:

records = table.objects.filter(
    geom__intersects = table.objects.filter(pk=1).values('geom')
)

但我仍然缺少缓冲区。
有什么建议吗?

经过一番研究,我通过以下方式解决了这个问题:

# First get the geometry i tried to get in the subquery
tempgeom = table.objects.get(pk=1)
# Apply the buffer
tempgeom = tempgeom.geom.buffer(10)
# Use the buffered geometry to get the records
records = table.objects.filter(geom__intersects = tempgeom)

我认为有更好的方法,但就目前而言,它有效。

您的解决方案是正确的@Chris。

唯一的添加可能是 Django 版本 1.11,其中添加了 Subquery

基本上您可以将 PostgreSQL 查询转换为以下内容:

records = table.objects.filter(
    geom__intersects=Subquery(
        table.objects.get(pk=1).geom.buffer(10)
    )
)

并避免中间步骤。