首页 > 解决方案 > 从 django 中的配置文件模型 __str__ 获取用户实例

问题描述

我有这个简单的模型:

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 来配置文件。

但在 Profile 模型中,我无法访问用户实例以仅在str方法中使用其电子邮件。像这样的东西:

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

我怎样才能做到这一点?有时这些关系让我感到困惑。

更新

是的 self.user.email 效果很好。但问题是别的。我有两种类型的用户。用户和老师。他们每个人的模型中都有字段配置文件。所以如果我说:

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

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

标签: pythondjango

解决方案


用户模型:

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)

推荐阅读