Skip to content Skip to sidebar Skip to footer

Django Return Two Separate __str__ For A Model Form

I have a Task model that includes tasks and a foreign key to entities: class Task(models.Model): task = models.CharField(max_length=500) entity = models.ForeignKey(Entity)

Solution 1:

Models in Django are just classes. You could also create property for type in Task class.

classTask(models.Mode):
    ... your code ...

    @propertydefentity_type(self):
        return'{}'.format(self.entity.type)

Then you'd call {{ form.instance.entity_type }} in template.

It's a bit of an overkill in this case, but it might be an option in more complex situations.

Solution 2:

In the template, form.instance.entity is the instance's related entity. If you want to display the type field, you can simply use:

{{ form.instance.entity.type }}

To answer the question in your title, each model can only have one __str__ method. You could define another method or property that returns a string, but there's no need to do this if you just want to display the type field.

Post a Comment for "Django Return Two Separate __str__ For A Model Form"