我有以下型号,我正在django shell中尝试这两个命令:
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
答案 0 :(得分:2)
您需要使用objects
属性来访问数据库值。
UserProfile.objects.get(user_id=2).birth_year
或
User.objects.get(id=2).profile.birth_year
您的所有代码都是使用UserProfile
user_id=2
的本地实例
https://docs.djangoproject.com/en/1.7/topics/db/models/#model-attributes