访问数据ManyToMany django模板

时间:2014-04-05 04:53:03

标签: django model many-to-many

我尝试显示菜单类别--->子类别--->产品。 我使用context_processor来显示所有类别和子菜单。 我需要根据类别和子类别获取产品 我只能在对象上显示django.db.models.fields.related.ManyRelatedManager ....

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 %}

1 个答案:

答案 0 :(得分:1)

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

在Python中你会得到一个TypeError: 'Manager' object is not iterable异常,但在模板中如果无声地失败......


还有一些调整要做......你似乎错了related_name。相关名称用于撤消关系,而不是跟随它们。所以这可能就是你所追求的:

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"

现在你可以做类似的事情:

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

    somestuff...

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

    somemorestuff...

P.S。

你可以完全忽略related_name。将使用默认相关名称:在此示例中为product_set