Geo Django子类化查询集



我正在使用geojango来搜索一堆不同类型的位置。例如,House和apartment模型都是Location的子类。

使用下面的子类化查询集,我可以做一些像Location.objects.all()这样的事情,并让它返回给我[<House: myhouse>, <House: yourhouse>, <Appartment: myappartment>],这是我的愿望。

但是,我还想确定到每个位置的距离。通常,在没有子类化Queryset的情况下,表2中的代码为我返回从给定点到每个位置....的距离[ (<Location: Location object>, Distance(m=866.092847284))]

但是,如果我尝试使用子类化查询集来查找距离,我会得到如下错误:

AttributeError: 'House'对象没有属性'distance'

你知道我如何保留返回子类对象的查询集的能力,但在子类对象上有可用的距离属性?如有任何建议,不胜感激。

展品1:

class SubclassingQuerySet(models.query.GeoQuerySet):
    def __getitem__(self, k):
        result = super(SubclassingQuerySet, self).__getitem__(k)
        if isinstance(result, models.Model) :
            return result.as_leaf_class()
        else :
            return result
    def __iter__(self):
        for item in super(SubclassingQuerySet, self).__iter__():
            yield item.as_leaf_class()
class LocationManager(models.GeoManager):
    def get_query_set(self):
        return SubclassingQuerySet(self.model)
class Location(models.Model):
    content_type = models.ForeignKey(ContentType,editable=False,null=True)
    objects = LocationManager()
class House(Location):
    address = models.CharField(max_length=255, blank=True, null=True)
    objects = LocationManager()
class Appartment(Location):
    address = models.CharField(max_length=255, blank=True, null=True)
    unit = models.CharField(max_length=255, blank=True, null=True)
    objects = LocationManager()

展品2:

from django.contrib.gis.measure import D 
from django.contrib.gis.geos import fromstr
ref_pnt =  fromstr('POINT(-87.627778 41.881944)')
location_objs = Location.objects.filter(
        point__distance_lte=(ref_pnt, D(m=1000) 
              )).distance(ref_pnt).order_by('distance')
[ (l, l.distance) for l in location_objs.distance(ref_pnt) ]   # <--- errors out here

我正忙着解决这个问题。这个怎么样:

class QuerySetManager(models.GeoManager):
    '''
    Generates a new QuerySet method and extends the original query object manager in the Model
    '''
    def get_query_set(self):
        return super(QuerySetManager, self).get_query_set()

您必须在所有子类中重新分配管理器。

来自Django文档:

定义在非抽象基类上的管理器不能被子类继承。如果希望从非抽象基类重用管理器,请在子类上显式地重新声明它。这些类型的管理器可能相当特定于定义它们的类,因此继承它们通常会导致意想不到的结果(特别是对于默认管理器而言)。因此,它们不会被传递给子类。

https://docs.djangoproject.com/en/dev/topics/db/managers/custom-managers-and-model-inheritance

最新更新