w--
w--

Reputation: 6697

django-model-utils, inheritance and templates

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

etc

Is there some other more elegant way of doing this?

Upvotes: 0

Views: 398

Answers (1)

jpic
jpic

Reputation: 33420

You can add a model method like:

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

Then:

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

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

etc, etc...

Upvotes: 1

Related Questions