【问题标题】:Why 'Model_name' object is not iterable?为什么“Model_name”对象不可迭代?
【发布时间】:2020-10-22 12:45:04
【问题描述】:

为什么我得到错误 { TypeError at /4 'Model_name' object is not iterable } 对于我的这段代码

destinations.html

                        {% for dest in dests %}
                        <div>{{dest.name}}</div>
                        {% endfor %}

urls.py

我不知道我错了什么

                   urlpatterns=[
                         path('',views.index,name='index'),
                         path('<int:destinations_id>', views.destinations, name='destinations'),
                        ]

views.py

当我通过“dests=Destination.objects.all()”获取模板上的所有模型行时,相同的“destinations.html”没有错误,但我只想要模板上的特定 id 行,所以我我正在使用“get_object_or_404”。

                    from django.shortcuts import get_object_or_404, render
                    from .models import Destination

                    def destinations(request, destinations_id):
                        dests = get_object_or_404(Destination, pk=destinations_id)
                        return render(request, 'destinations.html', {'dests':dests})

【问题讨论】:

    标签: django django-models django-rest-framework django-templates


    【解决方案1】:

    您不需要使用 for 循环,因为 get_object_or_404 只获得 1 个模型目标...

    如果您想获得所有可以使用的目的地的列表

    dests = Destination.objects.all()

    所以现在你可以使用 for 循环...

    【讨论】:

    • 感谢您的即时回复。我理解你所说的,并且成功了。
    【解决方案2】:

    出现问题是因为您通过使用仅获得一个对象实例 get_object_or_404 获取 不用循环你可以直接说

    <div>{{dest.name}}</div>
    

    但是如果你使用

    dests = Destination.objects.all()
    

    然后你可以使用循环作为

                            {% for dest in dests %}
                            <div>{{dest.name}}</div>
                            {% endfor %}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-01
      • 2021-05-16
      • 1970-01-01
      • 1970-01-01
      • 2018-05-18
      • 2020-04-09
      • 2017-08-25
      相关资源
      最近更新 更多