south迁移:“数据库后端不接受0作为AutoField的值”(mysql)

2024-05-16 02:34:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我是django的新手,我试图为一个受让人和记者将外键返回给用户。 但当我试图向南方申请变更时,我得到了一个错误

ValueError: The database backend does not accept 0 as a value for AutoField.

我的型号代码:

class Ticket(models.Model):
    title = models.CharField(max_length=80)
    text = models.TextField(blank=True)
    prioritys = models.ForeignKey(Prioritys)
    ticket_created = models.DateTimeField(auto_now_add=True)
    ticket_updated = models.DateTimeField(auto_now=True)
    assignee = models.ForeignKey(User, null=True, related_name='assignee')
    reporter = models.ForeignKey(User, null=True, related_name='reporter')

    def escaped_text(self):
        return markdown.markdown(self.text)

    def __unicode__(self):
        return self.text

Tags: textnameselftrueautomodelsreporterticket
3条回答

很久以前,Autofield有个问题。

https://code.djangoproject.com/ticket/17653

有趣的引语:

答:

It seems you are trying to save 0 to a ForeignKey which points to an AutoField. But, this is illegal, as the AutoField will not accept that value and so the ForeignKey can not hold that value either.

乙:

So this fix creates another problem when you need to be able to accept a value of 0 (or if you are working on a DB that already has a value of 0!) in an autofield. In my case, I need to accept an ID of zero so that my foreign key can point to zero so that a unique constraint can work properly.

看起来你在"user"."user_id"中有0
但是再一次。。。完整的堆栈跟踪,请。。。

我没有使用South,但是我最近从Django 1.4升级到了1.6(MySQL作为两者的db后端),并且在尝试保存一些模型时得到了相同的ValueError。我找到了一个递归外键字段。所以我有:

class Foo(models.Model):
    ...
    duplicate = models.ForeignKey('self', blank=True, null=True)
    ...

不幸的是,我不确定我的许多对象在哪里得到了0的值。

>>> Foo.objects.filter(duplicate_id=0).count()
2078

我的其他任何字段都没有出现这种情况,只有自引用字段。所以我将该字段的值设置回None,这就修复了错误。

>>> Foo.objects.filter(duplicate_id=0).update(duplicate=None)
2078L

由于此特定错误不会指向导致问题的特定字段,因此通常可以检查外键字段fieldname是否有任何0值:

>>> Foo.objects.filter(fieldname_id=0).count()

如果结果为非零,则可能需要修复该字段。

如果在旧版本中运行manage.py migrate(或manage.py syncdb)时发生这种情况,原因可能是您试图向使用AutoField作为主键并使用0作为默认值的模型添加外键。编辑迁移文件并删除AddField操作中的参数default=0在Django 1.10中对我有效。

相关问题 更多 >