[GIS] GeoDjango: Order by distance for model that has a ForeignKey relation to another model that has a PointField

geodjango

Model A has a ForeignKey relation to Model B. Model B has a PointField. Is there a way to order Model A objects by distance from a POINT?

Best Answer

Assuming that both Model A and B are using objects = models.GeoManager(), the FK field on Model A is named b, Model B has PointField named point, and pnt is a GEOSGeometry then the following should work:

A.objects.distance(pnt, field_name='b__point').order_by('distance')