Reputation: 11
Hello I have a little problem in Django, I created a database and now I want to print the queries of this, so I have in my user.py file the following code
def user(request):
user_list = User.objects
user_dict = {'user_data': user_list}
return render(request,'AppTwo/User.html',context=user_dict)
here i get the following error: User.py Exception Type: TypeError Exception Value: 'Manager' object is not iterable.
To fix this, I need to change the code to this:
def user(request):
user_list = User.objects.order_by('first_name')
user_dict = {'user_data': user_list}
return render(request,'AppTwo/User.html',context=user_dict)
but I can not understand why the simple adding of order_by('first_name'), casts the object to a list? Why do I need this? I have trouble to understand, maybe somebody could help me and explain to me what is happening here. Thank you very much in advance
Upvotes: 1
Views: 445
Reputation: 382
we need to iterate over the query result so to do that we have to give objects.all() or objects.order_by('name')
Upvotes: 0
Reputation: 13327
User.objects
doesn't return a result as a queryset, it's just the reference to the manager associated to the model.
A Manager is a class object which provides all the methods available to create queries and filters on the model.
You only obtain a queryset when you call these methods like all()
, filter
, order_by
...
A manager can even be overridden to provide special filters automatically, or you can also add extra managers in your model to use different filters/queries depending on the context.
Documentation :
Upvotes: 2