listing objects from ManyToManyField

霸气de小男生 提交于 2019-11-28 16:59:32

问题


I am trying to print a list of all the Conferences and for each conference, print its 3 Speakers.

In my template I have:

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

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

there is a model named conference. which has a class named Conferences with a ManyToManyField named speakers

I get the error:

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

with this line: {% for speakers in conference.speakers %}


回答1:


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



回答2:


Similar inside pythoncode this would be:

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


来源:https://stackoverflow.com/questions/2759520/listing-objects-from-manytomanyfield

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!