GeoDjango distance request for ForeignKey relationships

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 the modelB objects and sort them by distance from a given location (where the distance is defined as the distance between this location and the point object of the associated model A). When I try to run a query

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

I get an error

TypeError: ST_Distance output only available on GeometryFields. 

Note that loc is a Point object. However, when I run the request

modelB.objects.filter(modela__point__distance_lte = (loc, 1000)) 

This query works without errors and as expected.

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

Thank.

+3
source share
1 answer

For the first you will need to change it to:

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

if you want to see all the modelB objects.

".distance" QuerySet ( GeoQuerySet).

+5

Source: https://habr.com/ru/post/1793639/


All Articles