首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Geo Django子类Queryset

Geo Django子类Queryset
EN

Stack Overflow用户
提问于 2011-08-12 05:37:00
回答 2查看 1.1K关注 0票数 0

我正在使用GeoDjango搜索一堆不同类型的位置。例如,房屋和公寓模型都是位置的子类。

使用下面的子类查询集,我可以执行类似Location.objects.all()之类的操作,并让它返回给me [<House: myhouse>, <House: yourhouse>, <Appartment: myappartment>],这是我的愿望。

但是,我也想确定到每个地点的距离。通常,如果没有子类查询集,表2中的代码将返回从给定点到每个位置的距离.[ (<Location: Location object>, Distance(m=866.092847284))]

但是,如果我试图使用子类查询集找到距离,就会得到一个错误,例如:

AttributeError:“House”对象没有属性“距离”

您知道如何保留返回子类对象的查询集的能力,但子类对象上的距离属性可用吗?任何建议都是非常感谢的。

证物1:

代码语言:javascript
复制
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:

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2012-03-18 12:34:09

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

代码语言:javascript
复制
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()

其余的可以从这个DjangoSnippet开始。

票数 0
EN

Stack Overflow用户

发布于 2012-10-23 14:35:46

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

来自Django文件:

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

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/7035989

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档