简体   繁体   中英

primary key must be unique when extending table

I'm trying to add extend user model. I keep getting this error: Primary key is not unique .

class UserExtended(models.Model):
        user = models.OneToOneField(User, on_delete=models.CASCADE,parent_link=True,primary_key=True)

If I remove primary_key=True then I get the error instance.userextended.id does not exists well, of course it doesn't since now I dont have id.

How do I get around this?

In models.py

from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver

class UserExtended(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)

    # Then you can also add fields like these to extended model
    profilepic = models.ImageField(upload_to='uploads/users/%Y/%m/%d/', null=True, blank=True)
    designation = models.CharField(max_length=200,null=True, blank=True)
    about = models.TextField(null=True, blank=True)
    website = models.URLField(null=True,blank=True)


    def __str__(self):  
        return self.user.username

@receiver(post_save, sender=User)
def create_user_profile(sender, instance, created, **kwargs):
    if created:
        UserExtended.objects.create(user=instance)

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

Now, whenever a new user is created, a extended record for that user will be created automatically.

Also, if a user record is saved, then it will automatically be updated in extended record.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM