一般来说,对于此类查询来说,最好的 PostGIS 函数是ST_DWithin() http://postgis.org/documentation/manual-svn/ST_DWithin.html:
如果几何图形彼此之间在指定距离内,则返回 true。
例如。居住在#1 商店 1000 米范围内的所有顾客:
SELECT customers.*
FROM customers, shops
WHERE ST_DWithin(customers.the_geog, shops.the_geog, 1000)
AND shop.id = 1
ST_DWithin 将使用空间索引您应该已经创建了它,因此其性能优于 ST_Distance。
在 Django 中似乎有一个相应的过滤器,称为dwithin https://docs.djangoproject.com/en/dev/ref/contrib/gis/geoquerysets/#std:fieldlookup-distance_lte:
返回从查找几何体到几何体字段的距离在彼此给定距离内的模型。
Zipcode.objects.filter(poly__dwithin=(geom, D(m=5)))
Backend SQL Equivalent
PostGIS ST_DWithin(poly, geom, 5)
D(m=5) 返回长度为 5 米的距离对象
geom 是要计算到 Zipcode 对象距离的几何图形
dwithin() 是使用的函数
poly 是 Zipcode 对象的几何属性
z = Zipcode(code=77096, poly='POLYGON(( 10 10, 10 20, 20 20, 20 15, 10 10))')