0

I'm trying to create a customized User class inheriting from django User. Problem is I already have some users in database which can not be deleted whatsoever and also I have another class (let's say reports) which have a foreignkey to User. My question is: Is there any way to create my new User class and keep the old data too?
thanks in advance.

Bahman Rouhani
  • 1,139
  • 2
  • 14
  • 33
  • 1
    Do you really need two different User Classes? or might an attribute e.g. a role for the user be enough. What are you aiming for? – niklas Dec 16 '17 at 14:32
  • @niklas I want my users to be able to store multiple emails. right now my alternative is using a many-to-one relationship where I have an ExtraEmails class and that class has a foreign key to user model. – Bahman Rouhani Dec 18 '17 at 07:08

1 Answers1

1

You can create related model that links back to User. This is a common approach if you have different types of users, but there are also other use cases.

class SpecialUserProfile(models.Model):
    user = models.OneToOneField(User, null=True, blank=True, on_delete=models.SET_NULL)
    special_feature = models.CharField(max_length=100, null=True, blank=True)
    etc.

What you also need to do is create this profile, when new user is added to User. You can do this with post_save signal.

@receiver(post_save, sender=User)
def create_special_user_profile(sender, instance, created, **kwargs):

    if created:
        SpecialUserProfile.objects.create(user=instance)

You create profiles for existing user with a command or write and run a temporary function that does that for existing users in User.

Now you can use ORM in the sense of user.specialuserprofile.special_feature.

This way you'll keep using User model as a base, it won't mess with build-in user related functionalities, won't have think about new and old users and you can use this new model for any additional information about users.

Borut
  • 3,304
  • 2
  • 12
  • 18
  • thanks. that's a brilliant approach and more or less what I am doing right now. But if I change user to SpecialUserProfile.user I have to do a lot of changing in my code. that's why I was wondering if there was a way to inherit the User model without losing it's data. – Bahman Rouhani Dec 18 '17 at 07:14
  • 1
    Yes, changing base `User` model later in the project is difficult. This is the most elegant solution. For this reason it is recommended to always create custom `User` model by subclassing [`AbstractUser`](https://docs.djangoproject.com/en/dev/topics/auth/customizing/#using-a-custom-user-model-when-starting-a-project) when starting new project. But we all make mistakes, or forget about that. I know I forgot at least two times. – Borut Dec 18 '17 at 09:28