Search code examples
pythondjangoregistration

OneToOne connection between User and Profile in Django


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


Solution

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