Home > Back-end >  OneToOne connection between User and Profile in Django
OneToOne connection between User and Profile in Django

Time:05-23

I am creating an app in django in which after user model is created, via the signal I create a profile:

from django.contrib.auth.models import User
class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        Profile.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_user_profile(sender, instance, **kwargs):
    instance.profile.save()

But as far as I feel, this does not guarantees me that profile id always equals user's one

Is there any smart way to do this safer?

I think about creating a signal which will delete profile model after user one and opposite, but I still feel that not all cases are covered

CodePudding user response:

When you are creating a separate model linked in such a way, you can add primary_key = True to your OneToOne field eg,

user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True)

This will ensure you can use the same PK value for the User and the Profile.

CodePudding user response:

It's not recommended to use the built-in django User model. It's better to create your own User model, that inherits from AbstractUser. Then override the save method:

from django.contrib.auth.models import AbstractUser

class MyUser(AbtractUser)
    """ Add additional fields if you want """
    
    def __str__(self):
        return "something"

    def save(self, *args, **kwargs):
        Profile.objects.create(user=self)
        super(MyUser, self).save(*args, **kwargs)

You can also override the delete() and other model methods, read the documentation about it here: https://docs.djangoproject.com/en/4.0/topics/db/models/#overriding-predefined-model-methods

  • Related