我正在研究geodjango应用程序,我想在多边形中找到所有geogrpahic位置。我的想法是将所有地理信息(城市,国家,POI等)存储在一个表中,如果我想查找(多)多边形内的所有内容,我会查询数据库以找到这些点。
我有以下型号:
class Location(models.Model):
name = models.CharField(max_length=250, unique=True)
geometry = models.GeometryField(null=True, blank=True)
class Project(models.Model):
name = models.CharField(max_length=2000, blank=False, null=False, unique=True)
location = models.ManyToManyField(Location, related_name='projects', blank=True)
在我看来,我有: class LocationDetailView(DetailView): model =位置
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
location_geometry = self.get_object().geometry
location_projects = []
if 'Polygon' in location_geometry.geom_type:
# location is a Polygon or MultiPolygon
for loc in Location.objects.prefetch_related('projects').all():
if location_geometry.contains(loc.geometry):
for location_project in loc.projects.all():
location_projects.append({'name': location_project.name, 'pk': location_project.pk})
# Add in a QuerySet of all the projects
context['projects'] = location_projects
return context
这很慢(我在数据库中只有几百个位置)。正如您所看到的,我已经尝试通过预取项目来加快速度,但是当我查看调试工具栏中的SQL时,我看到(尽管它是一个快速查询),一个查询重复259次:
SELECT
"app_location"."id",
"app_location"."name",
"app_location"."geometry"::bytea,
FROM
"app_location" WHERE "app_location"."id" = 979
Duplicated 259 times.
这个查询被调用一次,但速度很慢:
SELECT
("app_project_location"."location_id") AS "_prefetch_related_val_location_id",
"app_project"."id",
"app_project"."name"
FROM
"app_project" INNER JOIN "app_project_location" ON
("app_project"."id" = "app_project_location"."project_id")
WHERE "app_project_location"."location_id" IN (780, ..., 1018, 1019, 1020, 1021, 1022, 1023)
我怎样才能更有效地做到这一点?我可以当然加载所有的对象,并在python中的poly部分做点,但我认为它可以直接在DB中完成?