Python django模型UTIL、继承和模板

Python django模型UTIL、继承和模板,python,django,django-models,django-templates,Python,Django,Django Models,Django Templates,因此,django模型utils非常棒。 我在django 1.3上,正在尝试使用继承管理器 我想要完成的是: -用于捕获所有子类的查询集 -将此查询集传递给模板 -迭代此查询集,但根据特定的子类对每个obj进行不同的处理 以文档中的示例为例,如果我这样做: nearby_places = Place.objects.filter(location='here').select_subclasses() 一旦我进入了一个模板,有没有办法让我知道附近的每个地方是什么,这样我就可以用它做一些不同的

因此,django模型utils非常棒。
我在django 1.3上,正在尝试使用继承管理器

我想要完成的是:
-用于捕获所有子类的查询集
-将此查询集传递给模板
-迭代此查询集,但根据特定的子类对每个obj进行不同的处理

以文档中的示例为例,如果我这样做:

nearby_places = Place.objects.filter(location='here').select_subclasses()
一旦我进入了一个模板,有没有办法让我知道附近的每个地方是什么,这样我就可以用它做一些不同的事情?e、 g

{% 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

还有其他更优雅的方法吗?

您可以添加如下模型方法:

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


最好只是将您需要的逻辑添加到模型本身,因为您已经有了很好的子类化。例如,使用像get_html_description之类的方法,或者任何您需要的方法。
{% if np.classname == 'Restaurent' %}
{% endif %}

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

etc, etc...