开发者

django - multiple queries into one

开发者 https://www.devze.com 2023-04-08 20:03 出处:网络
I want to find the Records with a certain tag within 100 mile radius. I have two queries that work independently (see below) but I don\'t know how to put them together.

I want to find the Records with a certain tag within 100 mile radius. I have two queries that work independently (see below) but I don't know how to put them together.

Also Records model has a foreign key pointing to the GeoLocation model called geo_location. I want to be able to show fields from both models (Records and GeoLocation) in one shot. I tried with .select_related() on the GeoLocation query below but for some reason I only get it to show the GeoLocation model fields and not the additional Records model fields as I expected.

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)

Any ideas?


These are my models:

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)开发者_JAVA技巧:
    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)

For the tags field in the Records model I'm using django-taggit.


There are two things wrong here.

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.)

0

精彩评论

暂无评论...
验证码 换一张
取 消