[Answer]-Access to data ManyToMany django template

1👍

{% for p in produtos.subcategoria.all %}  

In Python you would get a TypeError: 'Manager' object is not iterable exception, but in templates if fails silently…


There are some more tweaks to be done… You seem to got it wrong with the related_name. Related name is used for reversing relationships, not following them. So probably this is what you’re after:

class Categoria(models.Model):  # singular!
    nome_categoria = models.CharField(max_length=100)

class Subcategoria(models.Model):
    nome_subcategoria = models.CharField(max_length=100)    

class Product(models.Model):
    # using ForeignKey instead of ManyToMany. Guessed so because "categoria" is singular, right?
    categoria = models.ForeignKey('Categoria', related_name='produtos')  # plural in related_name, and "products" not "category"
    subcategoria = models.ForeignKey('Subcategoria', related_name='produtos')  # plural in related_name, and "products" not "category"

Now you can do stuff like:

{% for p in categoria.produtos.all %}

    somestuff...

    {% for sc in p.subcategoria.all %}

    somemorestuff...

P.S.

You can leave out the related_name altogether. A default related name will be used: product_set in this example.

👤frnhr

Leave a comment