Tamara
Tamara

Reputation: 75

Get value in template of ManyToMany ForeignKey field

I need to display the values of the categories field from the class Analiza from the models below in a template.

class Category(models.Model):
    name = models.CharField(max_length=60)
    def __unicode__(self):
        return self.name

class Analiza(models.Model):
    ...
    categories = models.ManyToManyField(Category, blank = True, null = True, verbose_name = "Категорија")
    ...

How do I do that? I've been reading documentation, but no reference to a situation of this kind (ManyToMany of ForeignKey).

Thanks in advance.

Upvotes: 0

Views: 1068

Answers (1)

Peter DeGlopper
Peter DeGlopper

Reputation: 37344

Given an instance of class Analiza, it will have a categories many-to-many field manager attribute that you can reference in your template:

<ul>
{% for category in obj.categories.all %}
    <li>{{ category }}</li>
{% endfor %}
</ul>

Or whatever - the point is that it'll be an iterable returning instances of Category.

Upvotes: 1

Related Questions