[英]How to get the value of Primary Key of any table for a particular row
在 django 中,我正在創建用戶,之后我想要用戶的 PK,然后我想將其放入其他表中。
我正在使用下面的代碼
id_profile = User.objects.filter(email = email)
id_profile = id_for_profile.values("id")
我在這里得到 output <QuerySet [{'id': 11}]>
但我想要與變量“id_profile”關聯的數字“11”
怎么做到呢?
[[解決了]]
它返回一個字典列表,我可以用這種方式訪問值。
或使用下面提供的答案。
User.objects.filter(email = email)
是列表。
嘗試
id_profile[0].id
或使用get
而不是filter
方法
id_profile = User.objects.get(email = email)
現在它將返回 object,並訪問pk
id_profile.pk
你可以試試這個:
id_profile = User.objects.get(pk=pk)
pk = id_profile.pk
您還可以使用內容類型
user_pk = ContentType.objects.get(app_label='auth',model='user').pk
因為email
字段是唯一的,所以您應該使用get
,因為 model 不會返回多個user
object。
您應該使用get_object_or_404
。 當 email 不存在時,將引發異常。
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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.