简体   繁体   中英

How to get the value of Primary Key of any table for a particular row

In django Im creating user, and after that I want the PK of the User and then I want to put it into some other table.

I am using the below code

id_profile = User.objects.filter(email = email)
id_profile = id_for_profile.values("id")

here im getting the output <QuerySet [{'id': 11}]>

but i want the Number "11" associated with the variable "id_profile"

How can it be done?

[[SOLVED]]

It is returning a List of Dictionaries, I can access the Values with that way.

or using the answers that were provided below.

User.objects.filter(email = email)

is list.

try with

id_profile[0].id

or use get rather than filter method

id_profile = User.objects.get(email = email)

now it will return a object,and access the pk

id_profile.pk

You can try this:

id_profile = User.objects.get(pk=pk)
pk = id_profile.pk

You can also use the contenttypes

user_pk = ContentType.objects.get(app_label='auth',model='user').pk

Because the email field is unique you should use a get as the model will not return more than one user object.

You should use get_object_or_404 . When the email does not exist an exception will be raised.

from django.shortcuts import get_object_or_404

user = get_object_or_404(User, email=email)
# to access the pk you can do this
user.pk

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM