私はGeoDjangoを使用して、さまざまなタイプの場所を検索しています。たとえば、HouseモデルとAppartmentモデルはどちらもLocationのサブクラスです。
以下のサブクラス化クエリセットを使用して、Location.objects.all()のようなことを実行し、それを返してもらうことができます[<House: myhouse>, <House: yourhouse>, <Appartment: myappartment>]
。これが私の望みです。
ただし、それぞれの場所までの距離も調べたいと思います。通常、サブクラス化クエリセットがない場合、別紙2のコードは、指定されたポイントから各場所までの距離を返します。[ (<Location: Location object>, Distance(m=866.092847284))]
ただし、サブクラス化クエリセットを使用して距離を検索しようとすると、次のようなエラーが発生します。
AttributeError:'House'オブジェクトに属性'distance'がありません
サブクラス化されたオブジェクトのクエリセットを返す機能を保持しながら、サブクラスオブジェクトで使用可能な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