1

我想在 100 英里半径范围内找到Records某个。tag我有两个独立工作的查询(见下文),但我不知道如何将它们放在一起。

模型还有Records一个指向模型的外键,GeoLocation称为geo_location. 我希望能够一次性显示模型(Records和) 的字段。GeoLocation我尝试了下面.select_related()GeoLocation查询,但由于某种原因,我只让它显示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)

对于模型tags中的字段,Records我使用django-taggit

4

1 回答 1

2

这里有两件事不对。

Firstly, you've misunderstood what select_related() does. It doesn't bring the fields from the related model into the current one. Instead, it just pre-fetches the related instance, so that doing the model_instance.foreignkey_field.field_on_related_model doesn't cause another db hit.

Secondly, your models contradict what you originally said about the foreignkey. You said it was from GeoLocation to Records, but the model definitions show that is the other way round. select_related does not work in that direction - there is no way, given your current models, to query GeoLocation and get the related Records in one go. However, you can query Records and get the related GeoLocations.

(Thirdly, your answer to my comment about the use of the single-element in lookup is completely irrelevant. Use tags_slug=tag.)

于 2011-09-28T14:24:45.477 回答