Reputation: 219
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
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
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