[Solved]-Django 'model' object is not iterable


Change Employee.objects.get(id=id) to Employee.objects.filter(id=id)

"filter() will always give you a QuerySet" – it’s iterable

get() – return single object and it’s not iterable



You are iterating over emp_item as an object list. But it is an object as Employee.objects.get(id=id) returns a single object rather than a queryset.

So what you need to do is remove the for-loop from the template as:

{% if emp_item %}
    <title> {{ emp_item.employee_name }} Report</title>

    <h3>{{ emp_item.employee_name }}</h3>
    ...and so on
{% else %}
<h2>No User</h2>
{% endif %}

But if you use get while querying, there is a higher chance that you can get an exception of DoesNotExist. So it is better if you can use Employee.objects.filter(id=id) to avoid any exceptions.

The {% if emp_item %} in your template is of no use if you are querying using get.

For better use, you can use get while querying and send a message to the template if exception occurs. For example:

def report(request, id):
        emp_item = Employee.objects.get(id=id)
        return render(request, 'projectfiles/report.html', {'emp_item':emp_item})
    except Employee.DoesNotExist:
        return render(request, 'projectfiles/report.html', {'error': 'No data found.'})

Then in template:

{% if error %}
    {{ error }}
{% else %}
    <title> {{ emp_item.employee_name }} Report</title>
    .... and so on to display other data
{% endif %}


I got the same error below:

TypeError: ‘Category’ object is not iterable

Because I assigned the object made by get() to category__in as shown below:

                         # Here                     # Here

So, I assigned the queryset made by filter() to category__in as shown below, then the error was solved:

                                                    # Here

Or, I removed __in from category__in as shown below, then the error was solved:

                       # ↓ "__in" is removed

Leave a comment