0

django-model-utils は素晴らしいです。
私はdjango 1.3を使用しており、継承マネージャーを使用しようとしています。

私が達成したいことは次のとおりです:
-すべてのサブクラスをキャプチャするクエリセット
-このクエリセットをテンプレートに渡す-このクエリセットを
反復処理しますが、特定のサブクラスに応じて各オブジェクトを異なる方法で扱います

私がそうする場合、ドキュメントから例を取ります:

nearby_places = Place.objects.filter(location='here').select_subclasses()

テンプレートに入ったら、nearly_places のそれぞれが何であるかを知る方法があるので、それを使って何か違うことができますか? 例えば

{% for np in nearby_places %}
{% if np is a restrautant %}
# do this
{% elif np is a bar %}
# do this
{% endif %}
{% endfor %}

今考えられる唯一のことは、各サブクラスで次のようなメソッドを定義する場合です

def is_restaurant()
    return True

def is_bar()
    return True

etc

これを行う他のよりエレガントな方法はありますか?

4

1 に答える 1

1

次のようなモデル メソッドを追加できます。

def classname(self):
    # can't access attributes that start with _  in a template
    return self.__class__.__name__

それで:

{% if np.classname == 'Restaurent' %}
{% endif %}

{% if np.classname == 'Bar' %}
{% endif %}

etc, etc...
于 2012-04-04T07:04:42.623 に答える