geodjango foreignkey距离

时间:2014-12-13 13:18:19

标签: django postgis geodjango

我正在努力处理复杂的Django查询,主要是因为我尝试做一些可能很复杂的事情。

基本上,我得到了这个:

models.py:

from django.contrib.gis.db import models

class Show(models.Model):
  name = models.CharField()

class Venue(models.Models):
  name = models.CharField()
  coords = models.PointField()
  objects = models.GeoManager()

class Representation(models.Model):
  datetime = models.DateTimeField()
  venue = models.ForeignKey(Venue)
  show = models.ForeignKey(Show)

现在,我想要做的是,获得5个接近用户的传入节目(user.geoloc是一个Point)。其中一个复杂的事情是,我的一些用户可能住在没有场地的区域,而且,如果没有足够的节目,我的解决方案就是在更大的区域内进行搜索。

view.py:

from django.contrib.gis.measure import D

DISTANCE_CLOSE = 1000 #arbitrary number

## this thing is not working, because it's not how it should be done
## but the logic is clearer in this
def get_nearest_shows_not_working(request): 
  list_shows = {}
  while len(list_shows<5)
    list_shows = Show.representation_set.filter(venue__coords__distance_lte=(user.geoloc, D(m=DISTANCE_CLOSE))).order_by('datetime'):[5]
    DISTANCE_CLOSE = int(DISTANCE_CLOSE*1.2)
  return render(request, 'template.html', locals())

def get_nearest_shows_ducktape(request):
  list_shows = set()
  while len(list_show) < 5:
    list_rep = Representation.objects.filter(venue__coords__distance_lte=(user.geoloc, D(m=DISTANCE_CLOSE))).order_by('datetime')
    for rep in list_rep:
      list_shows.add(rep.show)
    DISTANCE_CLOSE = int(DISTANCE_CLOSE*1.2)
  list_shows = list_shows[:5]
  return render(request, 'template.html', locals())

我错过了什么?在Python中,有一种唯一正确的方法可以做某事,而在这里,我只是搞乱复杂的事情,这看起来对我来说是不可思议的。

1 个答案:

答案 0 :(得分:1)

你需要这样的东西:

Show.representation_set.distance(user.geoloc, field_name='venue__coords') \
                       .order_by('distance')

不幸的是,GeoQuerySet方法(包括距离)不支持反转一对一或一对多关系。我已经为此创建了a feature request ticket

所以现在我认为你一直坚持:

  • Python中的一些黑客,并不总是高效(就像你写的那样)
  • 使用原始SQL查询
相关问题