GeoDjango对于外键关系的距离查询 [英] GeoDjango distance query for a ForeignKey Relationship
问题描述
我有以下模型(简化)
from django.contrib.gis.db import models as geomodels
modelB (geomodels.Model):
objects = geomodels.GeoManager()
modelA (geomodels.Model):
point = geomodels.PointField(unique=True)
mb = models.ForeignKey(modelB,related_name='modela')
objects = geomodels.GeoManager()
我试图找到所有的modelB对象,并将它们与给定位置的距离进行排序(其中距离定义为给定位置与关联的modelA的点对象之间的距离)。当我尝试运行查询
I am trying to find all modelB objects and sort them by distance from a given location (where distance is defined as distance between a given location and the point object of associated modelA). When I try to run the query
modelB.objects.distance((loc, field_name='modela__point')
我收到错误说
TypeError: ST_Distance output only available on GeometryFields.
请注意,loc是一个Point对象。但是,当我运行查询
Note that loc is a Point object.However, when I run the query
modelB.objects.filter(modela__point__distance_lte = (loc, 1000))
此查询工作没有错误和预期。
this query works without error and as expected.
任何想法这个错误可能是什么?我使用的是django 1.2.4 PostGis 1.5.2 PostGres 8.4。
Any idea what the mistake could be? I am using django 1.2.4, PostGis 1.5.2, PostGres 8.4.
谢谢。
推荐答案
对于第一个,您需要将其更改为:
For the first one, you will need to change it to:
modelB.objects.all().distance(loc, field_name='modela__point')
如果你想要查看所有的modelB对象。
if you want to see all modelB objects.
.distance用于计算和向QuerySet(或GeoQuerySet)的每个结果行添加一个距离字段。
The ".distance" is used to calculate and add a distance field to each resulting row of the QuerySet (or GeoQuerySet).
这篇关于GeoDjango对于外键关系的距离查询的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!