Ricardo
Ricardo

Reputation: 25

access to data ManyToMany django template

I try to display a menu category ---> Subcategory ---> products. I use a context_processor to display all the categories and submenus . I need to get products based on category and subcategory I can only display django.db.models.fields.related.ManyRelatedManager at object ....

class Categorias(models.Model):
nome_categoria = models.CharField(max_length=100)

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

class Product(models.Model):
categoria = models.ManyToManyField('Categorias')
subcategoria = models.ManyToManyField('Subcategoria')

context.py

def menu(request):
    return {'menucategoria': Categorias.objects.all(),}

def submenu(request):
return {'submenu': Subcategoria.objects.all(),}

menu.html

{% for c in menucategoria %} 
    <ul>
        <li class="block">
            <input type="checkbox" name="item" id="{{c.id}}" />   
            <label for="{{c.id}}">{{c}}</label>
            <ul class="options">
            {% for p in produtos.subcategoria.all %}                 
                <li><a href="">{{p}}</a></li>    
            {% endfor %}
            </ul>
        </li>
    </ul>
{% endfor %}

Upvotes: 0

Views: 1490

Answers (1)

frnhr
frnhr

Reputation: 12903

{% 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.

Upvotes: 1

Related Questions