UserProfile(user_id = 2)返回<userprofile:user =“”>,但UserProfile(user_id = 2).birth_year返回None </userprofile:>

时间:2014-10-09 15:56:03

标签: python django

我有以下型号,我正在django shell中尝试这两个命令:

  1. from auth_lifecycle.models import UserProfile
  2. UserProfile(user_id=2).birth_year
  3. 但它返回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
    

1 个答案:

答案 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