2011-08-12 48 views
0

我正在使用GeoDjango來搜索一堆不同類型的位置。例如,House和Appartment模型都是Location的子類。Geo Django繼承子查詢集

使用下面的子類化Queryset,我可以做一些像Location.objects.all(),並讓它返回給我[<House: myhouse>, <House: yourhouse>, <Appartment: myappartment>],這是我的願望。

但是,我也想確定到每個位置的距離。通常,如果沒有子類化查詢集,示例2中的代碼將返回給定點到每個位置的距離...... [ (<Location: Location object>, Distance(m=866.092847284))]

但是,如果我嘗試使用子類化查詢集查找距離,錯誤如:

AttributeError的:「房子」對象有沒有屬性「距離」

你知道我怎麼能保存的能力返回子類對象的查詢集尚未有子類可用的距離屬性對象?任何意見非常感謝。

圖表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 

回答

0

我很忙,試圖解決這一個。這個怎麼樣:

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

您必須在所有子類中重新分配經理。

從Django文檔:

Managers defined on non-abstract base classes are not inherited by child classes. If you want to reuse a manager from a non-abstract base, redeclare it explicitly on the child class. These sorts of managers are likely to be fairly specific to the class they are defined on, so inheriting them can often lead to unexpected results (particularly as far as the default manager goes). Therefore, they aren't passed onto child classes.

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