Django重复条目1062

时间:2019-11-13 21:36:09

标签: python mysql django

我跑了python manage.py migrate accounts zero之后遇到了错误, 我多次检查了模型,似乎一切正常,但是...!?

这是错误:

django.db.utils.IntegrityError: (1062, "Duplicate entry '1' for key 'accounts_post_user_id_ecf3e197_uniq'")

用户模型

class User(AbstractBaseUser):
    id = models.BigAutoField(primary_key=True)
    username = models.CharField(max_length=30, unique=True)
    email = models.EmailField(max_length=191, unique=True)
    email_verified = models.BooleanField(default=False)
    first_name = models.CharField(max_length=30)
    last_name = models.CharField(max_length=30, blank=True)
    is_active = models.BooleanField(default=True)
    is_staff = models.BooleanField(default=False)
    is_admin = models.BooleanField(default=False)
    is_verified = models.BooleanField(default=False)
    created_at = models.DateTimeField(auto_now_add=True)

    objects = UserManager()

    USERNAME_FIELD = 'username'
    EMAIL_FIELD = 'email'
    REQUIRED_FIELDS = ['email', 'first_name', 'last_name']

    def __str__(self):
        return self.username

    def has_perm(self, perm, obj=None):
        return self.is_admin

    def has_module_perms(self, app_label):
        return self.is_admin

发布模型:

class Post(models.Model):
    id = models.BigAutoField(primary_key=True)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    channel = models.ForeignKey(Channel, on_delete=models.CASCADE, null=True, blank=True)
    hashed_id = models.CharField(max_length=191)
    text = models.TextField(max_length=270)
    visits = models.IntegerField(default=0)
    comment_status = models.BooleanField(default=True)
    edited = models.BooleanField(default=False)
    signature = models.CharField(max_length=191)
    deleted_at = models.DateTimeField(null=True, blank=True)
    created_at = models.DateTimeField(auto_now_add=True)

有1位用户有2条帖子。

1 个答案:

答案 0 :(得分:0)

我在{strong> ForeignKey字段中添加了unique=False,就解决了这个问题。

我希望如果您的应用程序中发生此错误,那么此答案会帮助您。