GeoDjango distance query for a ForeignKey Relationship

不羁的心 提交于 2019-12-13 14:14:01

问题


I have the following models (simplified)

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

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')

I get an error saying

TypeError: ST_Distance output only available on GeometryFields. 

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.

Any idea what the mistake could be? I am using django 1.2.4, PostGis 1.5.2, PostGres 8.4.

Thanks.


回答1:


For the first one, you will need to change it to:

modelB.objects.all().distance(loc, field_name='modela__point')

if you want to see all modelB objects.

The ".distance" is used to calculate and add a distance field to each resulting row of the QuerySet (or GeoQuerySet).



来源:https://stackoverflow.com/questions/5068457/geodjango-distance-query-for-a-foreignkey-relationship

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!