从Django的个人档案模型__str__获取用户实例

时间:2019-05-18 07:23:08

标签: python django

我有一个简单的模型:

class Profile(models.Model):
bio             = models.CharField(max_length=300, blank=False)
location        = models.CharField(max_length=50, blank=
edu             = models.CharField(max_length=250, blank=True, null=False)
profession      = models.CharField(max_length=50, blank=True)
profile_image   = models.ImageField(
    upload_to=upload_image, blank=True, null=False)

def __str__(self):
    try: 
        return str(self.pk)
    except:
        return ""

和用户模型:

class User(AbstractBaseUser, UserTimeStamp):
    first_name  = models.CharField(max_length=50, blank=False, null=False)
    email       = models.EmailField(unique=True, blank=False, null=False)
    profile     = models.OneToOneField(Profile, on_delete=models.CASCADE)
    uuid        = models.UUIDField(
        db_index=True,
        default=uuid_lib.uuid4,
        editable=False
    )
    is_admin    = models.BooleanField(default=False, blank=False, null=False)
    is_staff    = models.BooleanField(default=False, blank=False, null=False)
    is_active   = models.BooleanField(default=True, blank=False, null=False)

    objects     = UserManager()

    USERNAME_FIELD = "email"

    def has_perm(self, perm, obj=None):
        return True

    def has_module_perms(self, perm_label):
        return True

在用户模型中可以看到,我有一个要配置的OneToOneField。

但是在个人档案模型中,我无法访问用户实例,而仅通过 str 方法使用其电子邮件。像这样的东西:

def __str__(self):
    return self.user.email

我该怎么做?有时候这些关系让我感到困惑。

已更新

是的self.user.email运作良好。但问题是另外一回事。 我有两种类型的用户。用户和老师。 他们每个人在模型中都有现场资料。所以如果我说:

def __str__(self):
    return self.user.email

它仅返回用户实例的电子邮件。老师呢?

1 个答案:

答案 0 :(得分:0)

用户模型:

class User(AbstractBaseUser, UserTimeStamp):
    profile     = models.OneToOneField(Profile, on_delete=models.CASCADE, related_name='user_profile')

老师模型:

class Teacher(AbstractBaseUser, UserTimeStamp):
    profile     = models.OneToOneField(Profile, on_delete=models.CASCADE, related_name='teacher_profile')

个人资料模型:

def __str__(self):
    if hasattr(self, 'user_profile'):
          # profile belong to user
          print(self.user_profile.pk)
    elif hasattr(self, 'teacher_profile'):
          # profile belong to teacher
          print(self.teacher_profile.pk)