0
我有以下模型,並正嘗試在django shell這兩個命令:用戶配置(USER_ID = 2)返回<用戶配置:用戶>,但用戶配置(USER_ID = 2).birth_year返回None
from auth_lifecycle.models import UserProfile
UserProfile(user_id=2).birth_year
但它的返回None
,儘管UserProfile(user_id=2)
返回<UserProfile: user>
。
這裏是查詢確認數據是否存在:
auth_lifecycle_db=# select * from auth_lifecycle_userprofile;
id | birth_year | user_id
----+------------+---------
1 | 1905 | 1
2 | 1910 | 2
(2 rows)
如何訪問birth_year屬性?
models.py
"""Defines a single extra user-profile field for the user-authentication
lifecycle demo project: Birth year
"""
from django.contrib.auth.models import User
from django.db import models
class UserProfile(models.Model):
"""Extra information about a user: Birth year and profile picture. See
the package doc for more info.
---NOTES---
Useful related SQL:
- `select id from auth_user where username <> 'admin';`
- `select * from auth_lifecycle_userprofile where user_id=(x,x,...);`
"""
# This line is required. Links UserProfile to a User model instance.
user = models.OneToOneField(User, related_name="profile")
# The additional attributes we wish to include.
birth_year = models.IntegerField(
blank=True,
verbose_name="Year you were born")
# Override the __str__() method to return out something meaningful
def __str__(self):
return self.user.username