K.J Fogang Fokoa
K.J Fogang Fokoa

Reputation: 219

how to get the value of an attribute (pk) using QuerySet

I am trying to get the value of the primary attribute (pk). How to do it ? Equivalence for this

SELECT id FROM User WHERE username="Fokoa"

Upvotes: 1

Views: 1182

Answers (2)

willeM_ Van Onsem
willeM_ Van Onsem

Reputation: 476557

You can use a .values_list(..) [Django-doc] for that:

from django.contrib.auth.models import User

User.objects.filter(username='Fokoa').values_list('pk', flat=True)

or we can conver this to a list of primary keys with:

from django.contrib.auth.models import User

list(User.objects.filter(username='Fokoa').values_list('id', flat=True))

That being said, it is not very common to query for a specific column in Django. It is good practice to see primary keys as "black box tokens", so not interpret these as integers process these. After all, summing up two primary keys frequently does not make much sense.

Upvotes: 1

Alex
Alex

Reputation: 2474

Multiple ways:

User.objects.filter(username='Fokoa').values_list('id', flat=True)

Or, if you know that username is unique:

user = User.objects.get(username='Fokoa')
user.id

Upvotes: 2

Related Questions