Nipun Garg
Nipun Garg

Reputation: 658

Whats the difference iterating over the queryset in these two ways?

I was using Django for building my project and came across these two ways.

One way is :

users = Users.objects.filter(is_verified=True)

for user in users:
    print user.user.id

And the second way is :

users = Users.objects.filter(is_verified=True)

for user in users:
    print user.id

At first I thought the first way wont work but it was working and was quite slow then the second way.

Upvotes: 0

Views: 72

Answers (2)

eugene
eugene

Reputation: 41665

First access user 's user' s id

Your User table has user field in it and you are accessing a_user.user.id

Second one access User table's id field

Upvotes: 1

Developer
Developer

Reputation: 2006

The first one is looking at the user property inside of the individual Users object.

Basically the first one is doing:

print users[x].user.id

The second is doing:

print users[x].id

where x is the current index in the for loop.

If there is a user property inside of the Users object, the first is correct. Otherwise you'd want to just access the id property of the individual Users object.

An example of the Users class for the first scenario would be:

class Users(object):
  user = User()

An example of the Users class for the second senario would be:

class Users(object):
  id = 0

I think what's likely happening is that when accessing the user property on the Users object, it may be querying the database again. If you can include the Users class definition it would be easier to understand the root problem.

Upvotes: 1

Related Questions