-2

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"

user=request.user
user=Clovek.objects.all().filter(user=user)
user=user[0]
prvni_prihlaseni=False
first=True
for i in user:
user2771714
  • 311
  • 1
  • 3
  • 15
  • http://docs.python.org/2/glossary.html#term-iterable the object user is not iterable and it make completly sense. the user, the list not the object (change that naming), is iterable (a list). – EsseTi Oct 03 '13 at 12:10
  • Question doesn't reflect true intentions / poor research was done. "but i want to iterate only one user, and every variable in that object, Because i want to know if any variable in object is blank or not". – Alvaro Oct 03 '13 at 12:44

3 Answers3

4

You cannot iterate a model object unless you defined __iter__ in the model.

Do you mean iterate the queryset returned by Clovek.objects.all().filter(user=user)? Then, I think it's a typo:

user = request.user
users = Clovek.objects.all().filter(user=user)
#   ^      v
user = users[0]
prvni_prihlaseni=False
first=True
for i in users:
#            ^
falsetru
  • 357,413
  • 63
  • 732
  • 636
1

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

Community
  • 1
  • 1
Alvaro
  • 11,797
  • 9
  • 40
  • 57
0

The problem lies here:

user=Clovek.objects.all().filter(user=user)
user=user[0]

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
  • even if i change the name of the variable, It doesnt work. user=request.user usera=Clovek.objects.all().filter(user=user) users=usera[0] prvni_prihlaseni=False first=True for i in users: – user2771714 Oct 03 '13 at 12:22
  • but i want to iterate only one user, and every variable in that object, Because i want to know if any variable in object is blank or not – user2771714 Oct 03 '13 at 12:40
  • You can access any field like this `users[0].field` or `user.field` if `user=users[0]`. No need to loop. –  Oct 03 '13 at 12:44