2012-04-04 100 views
0

所以django-model-utils很棒。
我在django 1.3上,试图使用继承管理器。django-model-utils,继承和模板

我想做到的是:
- 一个QuerySet捕捉到所有的子类
- 通过这个查询集到模板
- 遍历这个查询集,但对待每一OBJ不同,这取决于具体子类

回吐从文档的例子,如果我这样做:

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

有一次,我在一个模板是有没有办法,我知道每个nearby_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 

的方法是否有这样做的其他一些更优雅的方式?

回答

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... 
+0

甜蜜。看起来我想要什么。谢谢。 – 2012-04-04 07:13:58

+0

只需将模型本身需要的逻辑添加到模型中,因为您已经有了很好的子类。 例如,使用get_html_description之类的方法或任何你需要的方法。 – joshua 2013-03-12 20:01:04