difference between values() and only()

Viewed 12091

what's the difference between using:

Blabla.objects.values('field1', 'field2', 'field3')

and

Blabla.objects.only('field1', 'field2', 'field3')
4 Answers

The answers given so far are correct, but they don't mention some of the differences in terms of queries. I will just report them.

.get()

# User.objects.get(email='user@email.com').username
SELECT "users_user"."id", "users_user"."password", "users_user"."last_login", 
"users_user"."is_superuser", "users_user"."username", "users_user"."first_name", 
"users_user"."last_name", "users_user"."email", "users_user"."is_staff", "users_user"."is_active", 
"users_user"."date_joined", "users_user"."name"
FROM "users_user" 
WHERE "users_user"."email" = 'user@email.com'; args=('user@email.com',)

.only().get()

# User.objects.only('username').get(email='user@email.com')
SELECT "users_user"."id", "users_user"."username" 
FROM "users_user" 
WHERE "users_user"."email" = 'user@email.com'; args=('user@email.com',)

.values().get()

# User.objects.values('username').get(email='user@email.com')
SELECT "users_user"."username" 
FROM "users_user" 
WHERE "users_user"."email" = 'user@email.com'; args=('user@email.com',)

As you can see, only() will also select the id of the record. This is probably because of the fact that it will output a model that you can later use, as the other answers mentioned.

Related