user939708
user939708

Reputation:

How to distinguish between inherited models in Django templates?

I have 2 Django models - model A and model B. Model B inherits from model A.

class ModelA(models.Model):
    # Fields

class ModelB(ModelA):
    # More fields

I want to be able to treat each model differently in a templates as shown:

{% if obj.is_modelA %} <-- This is where my problem lies
    Do something
{% elif obj.is_modelB %} <-- This is where my problem lies
    Do something else
{% endif %}

I'm sure I could hack something together, but I'd really like to know if there is a preferred way of doing this.

Many thanks in advance :)

Upvotes: 1

Views: 187

Answers (2)

Chris Morgan
Chris Morgan

Reputation: 90902

I'd say do it in your model rather than as a comparison in the template as @zeekay suggests. That leads to an unpleasant dependency on an internal detail (if you changed your class name things would break).

I'd do it rather like this:

class ModelA(models.Model):
    is_such_and_such = False

class ModelB(ModelA):
    is_such_and_such = True

It could be done as a property with either isinstance or a comparison of self.__class__.__name__, but I think defining a real boolean is a better idea.

End result is that in your template you can have:

{% if obj.is_such_and_such %}
    ...
{% else %}
    ...
{% endif %}

I'd also be doing it as a feature-based thing rather than model-based. Think about how you have is_staff on the Django's own User model. It's not using separate classes there, but the idea applies. Make sure that as far as it lies with you what appears in the template makes sense to someone who knows nothing of the implementation in the backend.

Upvotes: 1

Zach Kelling
Zach Kelling

Reputation: 53879

Not sure if there is preferred way to do this. I'd probably add the model's name as a property:

@property
def model_name(self):
    return self.__class__.__name__

Upvotes: 0

Related Questions