【发布时间】:2013-03-07 06:12:05
【问题描述】:
我有这两个模型。
class Store(models.Model):
coords = models.PointField(null=True,blank=True)
objects = models.GeoManager()
class Product(models.Model):
stores = models.ManyToManyField(Store, null=True, blank=True)
objects = models.GeoManager()
我想按到某个点的距离对产品进行排序。如果 Product 中的 stores 字段是外键,我会这样做并且它可以工作。
pnt = GEOSGeometry('POINT(5 23)')
Product.objects.distance(pnt, field_name='stores__coords').order_by('distance')
但由于该字段是 ManyToMany 字段,因此它与
ValueError: <django.contrib.gis.db.models.fields.PointField: coords> is not in list
我有点预料到这一点,因为不清楚它应该使用哪个商店来计算距离,但有什么办法可以做到这一点。
我需要按到特定点的距离排序的产品列表。
【问题讨论】:
-
我也遇到了这个困难。也许这对 GeoDjango 是不可能的?也许必须为它创建一个原始 sql?
-
@JoeJ 我将发布我所做的作为可能的答案,但我不喜欢它。可能原始 SQL 可以工作,但我对空间查询等不太满意。看看答案,看看你的想法。
-
产品有
ManyToMany到Store,但拥有PointField的是商店。一个产品可以在 1 个或多个商店... 对于一个拥有超过 1 个商店的产品来说,距离是多少? 越低?越高 ?全部? -
@Liarez 好问题。就我而言,它是最接近的。我需要一个产品搜索,在地图上显示你周围的产品。
标签: django geodjango django-orm