【问题标题】:How do I display all of the attributes from a many-to-many relationship?如何显示多对多关系中的所有属性?
【发布时间】:2012-08-15 08:01:08
【问题描述】:

我的 Django 应用中有 2 个模型具有多对多关系。如何显示产品将拥有的每个类别?我在视图和模板中包含什么?

class Product(models.Model):
    website = models.CharField('Product name', max_length = 200)
    mutliple_cat = models.ManyToManyField(Multicat, null=True, blank=True)
    def __unicode__(self):
        return self.website

class Multicat(models.Model):
    mutlicat = models.CharField('Multi cat', max_length = 200, null=True, blank=True)
    mutlicat_url = models.CharField('Multi cat url', max_length = 200, null=True, blank=True)
    def __unicode__(self):
        return unicode(self.mutlicat)

这是我的看法:

product = Product.objects.order_by("website")

模板:

{% for prod in product %}
    {% for cat in prod.multiple_cat.all %}
            {{ cat.multicat }}
    {% endfor %}
{% endfor %} 

【问题讨论】:

    标签: django templates view model many-to-many


    【解决方案1】:

    假设您将一个名为 my_product 的变量中的 Product 传递给模板:

    {% for cat in my_product.multiple_cat.all %}
        multicat name: {{ cat.multicat }}
        multicat url: {{ cat.multicat_url }}
    {% endfor %}
    

    【讨论】:

    • 我将我的观点包括在内......我正在传递“产品”。我尝试将其放入模板中,但没有任何反应。我的观点有问题吗?
    • 您的product 是所有产品的查询集,而不是单个实例。您需要在外部 for 循环中对其进行迭代。
    • 我也在尝试,但它似乎不起作用。我现在编辑了问题以在模板中包含 2 个 for 循环……for 循环的构造是否不正确?
    猜你喜欢
    • 2011-01-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-29
    相关资源
    最近更新 更多