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"

2 Answers

1
Willem Van Onsem On Best Solutions

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.

2
Alex On

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