列出ManyToManyField中的对象

时间:2010-05-03 16:23:42

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

我正在尝试打印所有会议的列表,并为每个会议打印3个演讲者。

在我的模板中,我有:

{% if conferences %}
        <ul>
        {% for conference in conferences %}
                <li>{{ conference.date }}</li>
                {% for speakers in conference.speakers %}
                        <li>{{ conference.speakers }}</li>
                {% endfor %}
        {% endfor %}
        </ul>
{% else %}
<p>No Conferences</p>
{% endif %}

在我的views.py文件中:

from django.shortcuts import render_to_response
from youthconf.conference.models import Conference

def manageconf(request):
        conferences = Conference.objects.all().order_by('-date')[:5]
        return render_to_response('conference/manageconf.html', {'conferences': conferences})

有一个名为会议的模型。它有一个名为会议的类,其中 ManyToManyField 名为发言人

我收到错误:

Caught an exception while rendering: 'ManyRelatedManager' object is not iterable

使用此行:{% for speakers in conference.speakers %}

2 个答案:

答案 0 :(得分:93)

您需要在多对多字段上调用all以获取可迭代对象。此外,下一行应包含扬声器而不是conference.speakers

{% for speaker in conference.speakers.all %}
        <li>{{ speaker }}</li>
{% endfor %}

答案 1 :(得分:16)

类似于pythoncode,这将是:

for speaker in conferenece.speakers.all():
  print speaker.FIELDNAME