2011-09-28 3 views
1

반경 100 마일 이내의 특정 tagRecords을 찾고 싶습니다. 독립적으로 작동하는 두 가지 쿼리가 있지만 (아래 참조) 나는 이들을 조합하는 방법을 모릅니다.django - 하나에 여러 쿼리

Records 모델에는 geo_location이라는 GeoLocation 모델을 가리키는 외래 키가 있습니다. 두 모델 (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) 

아이디어가 있으십니까? 내가 django-taggit를 사용하고있어 Records 모델의 tags 필드에서

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) 

:


이들은

내 모델입니다.

+1

1. 실제 모델을 제시해주십시오. 2. 왜'tags__slug = tag'가 아닌 단일 요소 목록으로'in'을 사용하고 있습니까? 3. 'GeoLocation'객체가 관련 '레코드'를 미리 가져 오지 않았 음을 어떻게 알 수 있습니까? –

+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을 수행하면 다른 db 히트가 발생하지 않습니다.

두 번째로, 모델이 원래 외래 키에 대해 말한 것과 모순됩니다. GeoLocation에서 Records에 이르렀다 고 했지요.하지만 모델 정의에 따르면 이것이 다른 방식입니다. select_related이 그 방향으로 작동하지 않습니다. 현재 모델에서 GeoLocation을 쿼리하고 관련 레코드를 한 번에 가져 오는 방법은 없습니다. 그러나 수 있습니다 쿼리 기록 및 관련 GeoLocations를 얻을.

은 (셋째, 단일 요소 in 조회의 사용에 대한 내 댓글에 대한 당신의 대답은 완전히 무관하다. tags_slug=tag를 사용합니다.)

+0

select_related가 작동하는 방식과 태그 필터의 문제를 명확히 해 주셔서 감사합니다. GeoLocation에서 다른 곳으로 갔을 때의 기록이라고 말했을 때 나는 실수했습니다. 나는 처음에 질문해야했던 것을 반영하기 위해 질문을 편집했다. 여전히 한 가지 질문이 남아 있습니다. 위의 모델을 고려하여 반경 100 마일 이내에있는 특정 태그가있는 레코드를 찾는 방법이 있습니까? 시간과 도움에 감사드립니다. – avatar