简体   繁体   中英

Get user instance from profile model __str__ in django

I have this simple model:

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 ""

and a User model:

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

As you can see in User model I have a OneToOneField to Profile.

but in Profile model I can't access user instance to just use its email in str method. something like this:

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

How can I do this? sometime these relations are confusing to me.

UPDATED

Yes self.user.email works well. but the problem is something else. I have two type of users. users and teachers. and each of them has field profile in their model. so if I say:

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

It just returns email of user instances. what about teachers?

user model:

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

teacher model:

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

profile model:

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM