2014-12-13 128 views
0

我正在努力處理複雜的Django查詢,主要是因爲我試圖做一些可能很複雜的事情。geodjango foreignkey的距離

基本上,我得到這個:

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中,應該是唯一正確的做事方式,在這裏,我只是搞亂了複雜的事情,這對我來說看起來並不矛盾。

回答

1

您需要像這樣:

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

不幸的是相反的一對一或一對多的關係,不與GeoQuerySet方法(包括遠程)的支持。我已經爲此創建了a feature request ticket

所以現在我想你堅持:

  • 一些黑客在Python中,並不總是有效的(就像你寫的),使用原始的SQL
  • 查詢