0

私は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
4

2 に答える 2

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から続くことができます。

于 2012-03-18T12:34:09.510 に答える
0

すべてのサブクラスでマネージャーを再割り当てする必要があります。

Django のドキュメントから:

非抽象基本クラスで定義されたマネージャーは、子クラスに継承されません。非抽象ベースからマネージャーを再利用する場合は、子クラスで明示的に再宣言します。これらの種類のマネージャーは、定義されているクラスにかなり固有である可能性が高いため、それらを継承すると、予期しない結果が生じることがよくあります (特にデフォルトのマネージャーに関する限り)。したがって、子クラスには渡されません。

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

于 2012-10-23T14:35:46.753 に答える