从Django中的Profile Model __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。

但是在配置文件模型中,我无法访问用户实例,只能在 str 方法中使用其电子邮件。这样的东西:

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

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

更新

是self.user.mail效果很好。但是问题是其他的。我有两种用户。用户和老师。他们每个人都有模型中的现场概况。因此,如果我说:

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

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

用户模型:

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)

相关内容

最新更新