相关模型的GeoDjango距离

相关模型的GeoDjango距离

本文介绍了相关模型的GeoDjango距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试返回一个距相关模型的距离的查询集.

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

models.py(简体)

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)

我需要返回的是Label对象,这些对象具有从到给定点的距离按顺序排列的某些标记.

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

我想做的是在 Label 表上执行查询以返回所有内容,但我怀疑这是不可能的.

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

在查询集上尝试 distance 方法会导致:

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.

推荐答案

绝对有可能实现您的查询:

It is definitely possible to achieve your query:

  • 使用 annotate() 将距离值附加到每个 Label 对象上.
  • 使用 Distance() 函数来计算每个商店的 geopoint location
  • 之间的距离
  • 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

查询应如下所示:

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

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

这篇关于相关模型的GeoDjango距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-04 12:18