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