Object is not iterable in django


When i try to iterate object from database in Django, It give me an error. I dont know really why. It give me precisely this error: "'Clovek' object is not iterable"

for i in user:


The problem lies here:


just set a different variable name. Don't use the same for both.

You cannot loop over user. the variable user in your code is set to user[0] which is not iterable. You need to loop over the query set Clovek.objects.all().filter(user=user) so that it prints the result.

This will work:

users = Clovek.objects.all().filter(user=user)
for i in users:
    print i

This won't work:

users = Clovek.objects.all().filter(user=user)
user = users[0]
for i in user: # user is not an iterable but users is. 
    print i

An example:

users = Clovek.objects.all().filter(user=user)
# in case there's only 1 result.
# user = users[0]
# you can access any of its field
# user.id, user.whatever

# in case there's more than 1:
for i in users:
    print i.id
By : moenad

After reading your comments, and figuring out what you wanted to do, found this, to iterate over a model's fields:

model._meta.get_all_field_names() will give you all the model's field names, then you can use model._meta.get_field() to work your way to the verbose name, and getattr() to get the value from the model.

from this post

By : Alvaro

This video can help you solving your question :)
By: admin