H C
H C

Reputation: 1200

How to display __str__ method in template in Django?

I have the following models:

class Work_Music(MPTTModel, Work):
    name = models.CharField(max_length=10, null=True, blank=True)


class Cast(models.Model):
    name = models.CharField(max_length=100, null=True, blank=True)

    def __str__(self):
        return self.name


class WorkCast(models.Model):
    work = models.ForeignKey(Work_Music, verbose_name=_('work'), related_name='workcast', null=True, blank=True, on_delete=models.PROTECT)
    cast = models.ManyToManyField(Cast, verbose_name=_('cast'), related_name='workcast', blank=True)

    def __str__(self):
        return "%s" % (
            ", ".join(character.name for character in self.cast.all())
        )

This will output: Character #1, Character #2, Character #3.

I pass in my view.py this QuerySet as context:

work = Work_Music.objects.get(pk=self.kwargs['pk']).get_descendants(include_self=False)

How do display the string that is returned when you call an instance of the WorkCast model (e.g. "Character #1, Character #2, Character #3")?

I have this currently:

{{ work.workcast }}

and it displays None

Upvotes: 4

Views: 2953

Answers (1)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 477338

Since you query a ForeignKey in reverse, the number of related WorkCast models is a collection that can contain zero, one, or more WorkCast objects. You thus should iterate over it, like:

{% for workcast in work.workcast.all %}
    {{ workcast }}
{% endfor %}

Upvotes: 4

Related Questions