我正在使用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