Django报错:'Manager'对象不可迭代,模板遍历数据遇问题求助
That error pops up because you’re trying to loop over a Django model Manager object instead of an iterable queryset. Here’s how to fix it:
Why This Happens
In your view, you’re probably passing the model’s manager (e.g., Main.objects) or the model class directly to the template context, instead of a queryset (like the result of .all(), .filter(), etc.). Managers aren’t iterable—they’re tools to create querysets that you can loop through.
Step 1: Correct Your View Code
Let’s say your current view looks like this (the problematic version):
from django.shortcuts import render from .models import Main def main_view(request): # Wrong: Passing the Manager instead of a queryset context = {'main': Main.objects} return render(request, 'your_template.html', context)
Change it to pass an iterable queryset instead. Use .all() to fetch all objects, or another query method if you need filtered results:
from django.shortcuts import render from .models import Main def main_view(request): # Correct: Pass an iterable queryset context = {'main': Main.objects.all()} return render(request, 'your_template.html', context)
Step 2: Verify Your Template
Your existing template code is fine as long as main is now a queryset. You can even add a fallback for empty data to make it more robust:
<h1>The Values are:</h1> {% if main %} <table> {% for obj in main %} <tr> <td>{{ obj.isTremor }}</td> <td>{{ obj.isFall }}</td> </tr> {% endfor %} </table> {% else %} <p>No data available to display.</p> {% endif %}
Quick Extra Tips
- If you only need specific objects, use
.filter()instead of.all()(e.g.,Main.objects.filter(isFall=True)). - Double-check you’re not accidentally passing the model class itself (like
context = {'main': Main})—that will trigger the same error too.
内容的提问来源于stack exchange,提问作者Parth Jeet

