unsafe_where_true
unsafe_where_true

Reputation: 6300

python/django: correct way of calling subclass method

I have a class BaseUser and a class RegisteredUser (AbstractBaseUser is a django class)

class BaseUser(AbstractBaseUser):
    #std properties of a base user

class RegisteredUser(BaseUser):
    def send_welcome_email(self):
      #send the email

A user can be invited to the platform, then she gets a TempLogin:

class TempLogin(models.Model):
   login_code:  models.CharField(max_length=255, unique=True)
   user:   models.ForeignKey(BaseUser, unique=True)

Thus the user has a login_code associated with it. It needs to be on BaseUser because other user types are supported.

Then, when the user arrives to the platform with her code, I look up the code, and get the user:

     code  = TemporaryLoginCode.objects.get(code=pk)
     user  = code.user
     user.send_welcome_email() 

The last bit breaks because send_welcome_email() is on RegisteredUser, not BaseUser.

I can't move send_welcome_email() to RegisteredUser apparently (third party code).

How can I have user become a RegisteredUser instance? Do I need to do another lookup on the DB, with the user id as key, in order to retrieve its RegisteredUser instance? Or is there another way?

I know I can't use super() as RegisteredUser is a subclass of BaseUser, not the other way around.

Upvotes: 1

Views: 134

Answers (2)

professorDante
professorDante

Reputation: 2405

You can't. You have defined the relationship as to BaseUser. It sounds like the send_welcome_email should be on RegisteredUser, as you are registered, and you get a welcome email. I would suggest when a user gets registered temporarily, they are not a registered user. Why not have a class TemporaryUser, which has a method send_temp_welcome_email, and have your code do this

class TempUser(BaseUser):
     def send_temp_welcome_email(self):
     #send the tempemail

class TempLogin(models.Model):
   login_code:  models.CharField(max_length=255, unique=True)
   user:   models.ForeignKey(TempUser, unique=True)

 code  = TemporaryLoginCode.objects.get(code=pk)
 user  = code.user
 user.send_temp_welcome_email() 

Upvotes: 1

Tiago Framesqui
Tiago Framesqui

Reputation: 463

Have you tried to def the send_welcome_email() in BaseUser (if you have all you need there) and def same method in RegisteredUser calling super().send_welcome_email()?

I didn't understand which code is thirdy part because you have your BaseUser and you mentioned that RegisteredUser is thirdy part but is inherited from you BaseUser.

Upvotes: 0

Related Questions