2011-09-28 69 views
1

我想在100英里半徑範圍內找到Records以及某個tag。我有兩個獨立工作的查詢(見下文),但我不知道如何將它們放在一起。django - 將多個查詢合併爲一個

另外Records模型有一個外鍵指向GeoLocation模型稱爲geo_location。我希望能夠一次性顯示來自(RecordsGeoLocation兩個型號的字段)。我在GeoLocation查詢下嘗試.select_related(),但由於某種原因,我只能按照我的預期顯示GeoLocation模型字段,而不是其他Records模型字段。

tag_search = Records.objects.filter(tags__slug__in=[tag]) 
geo_search = GeoLocation.objects.select_related().filter(srid2163__distance_lte=(pnt, D(mi=100))).distance(pnt) 

任何想法?


這是我的模型:

from taggit.managers import TaggableManager 
from django.contrib.gis.db import models 

class GeoLocation (models.Model): 
    lat = models.FloatField(blank=True) 
    long = models.FloatField(blank=True) 
    srid2163 = models.PointField(blank=True,srid=2163) 
    server_time = models.DateTimeField(auto_now_add=True) 

    objects = models.GeoManager() 

    def __unicode__(self): 
     return u'%s %s %s' % (self.lat, self.long, self.server_time) 


class Records(models.Model): 
    title = models.CharField(blank=True, max_length=50) 
    message_body = models.TextField() 
    server_time = models.DateTimeField(auto_now_add=True) 
    geo_location = models.ForeignKey(GeoLocation, related_name='geoloc') 


    tags = TaggableManager() 

    def __unicode__(self): 
     return u'%s %s %s' % (self.title, self.message_body, self.server_time) 

對於我使用django-taggitRecords模式tags領域。

+1

1.請出示實際的模型。 2.爲什麼你用單元列表而不是'tags__slug = tag'來使用'in'? 3.你如何看待你的'GeoLocation'對象沒有預取相關的'Record'? –

+0

@Daniel Roseman 1.看看上面的模型。 2.那是因爲我使用djago-taggit作爲標籤字段來搜索標籤。 3.我在我的模板中測試了{geo_search%} {{geo.lat}} {{geo.title}} {%endfor%}。我可以看到{{geo.lat}}的內容,但不能看到{{geo.title}}。 – avatar

回答

1

這裏有兩個錯誤。

首先,你誤解了select_related()的作用。它不會將相關模型中的字段導入當前模型。相反,它只是預取相關實例,以便執行model_instance.foreignkey_field.field_on_related_model不會導致另一個數據庫命中。其次,你的模型與你最初對外鍵的描述相矛盾。你說這是從GeoLocation到Records,但模型定義表明這是相反的。 select_related不能在那個方向上工作 - 根據您當前的模型,您無法一次查詢GeoLocation並獲取相關記錄。但是,您可以查詢查詢記錄並獲取相關的GeoLocations。

(第三,你回答我有關使用單元素in查找的評論是完全不相干的。使用tags_slug=tag

+0

感謝您澄清select_related如何工作以及標記過濾器的問題。你是對的,當我說它是從GeoLocation到Records時,我就搞砸了,那是另一回事 - 對此感到遺憾。我編輯了這個問題,以反映我應該首先提出的問題。仍然有一個問題。考慮到上述模型,有沒有辦法在100英里半徑內找到具有特定標籤的記錄?感謝您的時間和幫助。 – avatar