从 ManyToManyField 列出对象 [英] listing objects from ManyToManyField
本文介绍了从 ManyToManyField 列出对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试打印所有会议的列表,并为每个会议打印其 3 位发言人.
I am trying to print a list of all the Conferences and for each conference, print its 3 Speakers.
在我的模板中,我有:
{% 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 文件中:
in my views.py file I have:
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})
有一个名为会议的模型.它有一个名为 Conferences 的类和一个名为 speakers
there is a model named conference. which has a class named Conferences with a ManyToManyField named speakers
我收到错误:
Caught an exception while rendering: 'ManyRelatedManager' object is not iterable
用这一行:{% for speaks in meeting.speakers %}
推荐答案
您需要在多对多字段上调用 all
以获取可迭代对象.此外,下一行应包含发言人而不是 conference.speakers
.
You need to call all
on the many-to-many field to get an iterable object. Also, the next line should contain the speaker rather than conference.speakers
.
{% for speaker in conference.speakers.all %}
<li>{{ speaker }}</li>
{% endfor %}
这篇关于从 ManyToManyField 列出对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文