如何迭代 Django 模板标签中的 ManyToMany 字段?

Rya*_*yan 3 python django django-templates django-models django-views

我有一个包含多对多字段的对象。我试图在 Django 模板中迭代这个字段,但显然我不能。让我先向您展示代码。

模型.py:

class Book(models.Model):
    title = models.CharField(max_length = 100, blank=True)
    category = models.ManyToManyField(Category)

    def __str__(self):
        return self.title
Run Code Online (Sandbox Code Playgroud)

视图.py:

def book_list(request):
    books = Book.objects.all().order_by('-pk')
        
    context = {
        'books' : books,
    }
    return render(request, 'contents/book_list.html', context)
Run Code Online (Sandbox Code Playgroud)

模板文件:

{% for b in books %}
<div>
    {{b.title}}
    {% for cat in b.category %}
    {{cat}}
    {% endfor %}
</div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

现在我收到'ManyRelatedManager' object is not iterable错误。如何迭代该字段并显示category每个对象中的所有内容?

Nix*_*row 7

这是因为如果你调用b.category它只会返回关系对象。要获取其值(category对象),您必须添加.all. 像这样:

{% for b in books %}
<div>
    {{ b.title }}
    {% for cat in b.category.all %}
        {{cat}}
    {% endfor %}
</div>
{% endfor %}
Run Code Online (Sandbox Code Playgroud)

顺便说一下,我也改成了c.titleb.title因为我假设你想要这本书的书名,而不是来自全球的书名。