django-model-utils, inheritance and templates

Go To


so django-model-utils is awesome.
I'm on django 1.3 and attempting to use the Inheritance Manager.

What I want to accomplish is:
- a queryset to capture all subclasses
- pass this queryset to template
- iterate through this queryset but treat each obj differently depending on the specific subclass

taking the example from the docs if i do:

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

Once I'm in a template is there a way for me to know what each of the nearby_places is so i can do something different with it? e.g.

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

The only thing i can think of right now is if in each of my subclasses I define a method like

def is_restaurant()
    return True

def is_bar()
    return True


Is there some other more elegant way of doing this?

2012-04-04 06:24
by w--


You can add a model method like:

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-04 07:04
by jpic
sweet. that looks lk what i want. thx - w-- 2012-04-04 07:13
Better to just add the logic you need to the model itself since you have nice subclassing already.

For example use a method like gethtmldescription or whatever it is you need - joshua 2013-03-12 20:01