本文介绍了从ManyToManyField中列出对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



在我的模板中,我有:

  {%if meetings%} 
< ul>
{%会议中的会议%}
< li> {{conference.date}}< / li>
{%for conference.speakers%}
< li> {{conference.speakers}}< / li>
{%endfor%}
{%endfor%}
< / ul>
{%else%}
< p>否会议< / p>
{%endif%}

在我的views.py文件中我有:

  from django.shortcuts import render_to_response 
from youthconf.conference.models import会议

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

有一个名为会议的模型。其中有一个名为会议的类,名为演讲者



我得到错误:

 呈现时捕获异常:'ManyRelatedManager'对象不可迭代

此行: {%for conference.speakers%}

解决方案

您需要在多对多字段上调用 all 来获取一个迭代目的。另外,下一行应该包含说话者,而不是 conference.speakers

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


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

解决方案

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中列出对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-28 15:39