扩展表

时间:2017-09-02 15:50:49

标签: python django

我正在尝试添加扩展用户模型。我一直收到此错误:Primary key is not unique

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

如果我删除primary_key=True,那么我会收到错误instance.userextended.id does not exists,当然它不会因为我现在没有id。

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:0)

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()

现在,无论何时创建新用户,都会自动创建该用户的扩展记录。

此外,如果保存了用户记录,则会在扩展记录中自动更新。