Reputation: 637
I'm trying to use manytomany field but I'm so confused. what i'm trying to achive is; inside food category i want to show links for fries, steak,potato category pages. I'm trying to do it like this;
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
related_cat = models.ManyToManyField('self')
{% if category.related_cat %}
{{category.related_cat.name}}
{% endif %}
But this shows none... I'm so confused with this...can someone please clarify and direct me what I should do?
Upvotes: 0
Views: 45
Reputation: 43870
Since your field, related_cat
, is a ManyToManyField, it's reference can contain more than 1 object.
To access the objects in a ManyToManyField try:
{% if category.related_cat %}
{% for related_category in category.related_cat.all %}
{{related_category.name}}
{% endfor %}
{% endif %}
For other examples:
https://docs.djangoproject.com/en/1.9/topics/db/examples/many_to_many/#many-to-many-relationships
Upvotes: 3