【发布时间】:2015-02-12 01:59:54
【问题描述】:
我正在为复杂的 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 是一个点)。复杂的事情之一是我的一些用户可能住在没有场地的区域,我的解决方案是,如果他们附近没有足够的节目,则在更大的区域进行搜索。
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 中,应该有一种也是唯一正确的方法来做某事,而在这里,我只是在处理复杂的事情,这对我来说看起来很不合 Python。
【问题讨论】: