djangodatabasedjango-queryset

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"

Solution

  • 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.