GeoDjango distance of related model

浪尽此生 提交于 2021-02-07 19:44:48

问题


I'm trying to return a queryset with distances from a related model.

models.py (simplified)

class Store(models.Model):
    geopoint = models.PointField(srid=4326)

    objects = models.GeoManager()


class HashTag(models.Model):
    tag = models.CharField(max_length=100)


class Label(models.Model):
    hashtags = models.ManyToManyField(HashTag)
    store = models.ForeignKey(Store)

What I need to return are the Label objects which have a certain tag/tags ordered by distance from a given point.

The Labels can be found by:

Label.objects.filter(hashtags__in=tags)

Distances are available on Store objects calculated with:

Store.objects.filter(label__hashtags__in=tags)
             .distance(location).order_by('distance')

What I'd like to do is perform a query on the Label table to return everything but I suspect this is not possible.

Trying the distance method on the queryset results in:

TypeError: ST_Distance output only available on GeometryFields.

Failing that it would make sense to do the most efficient next best thing. The only solution I can come up with is to perform both queries and merge the results into a set.


回答1:


It is definitely possible to achieve your query:

  • Use the annotate() to append a distance value on every Label object.
  • Use the Distance() function to calculate the distance between each store's geopoint and the location point

The query should look like this:

from django.contrib.gis.db.models.functions import Distance

Label.objects.filter(hashtags__in=tags)
             .annotate(distance=Distance('store__geopoint', location))
             .order_by('distance')


来源:https://stackoverflow.com/questions/30082265/geodjango-distance-of-related-model

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