Django认为我没有ID字段

时间:2019-01-19 14:40:29

标签: django python-3.x sqlite

我创建了以下模型:

class World(models.Model):
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    name = models.CharField(max_length=200)
    setting = models.CharField(max_length=200)
    creation_date = models.DateTimeField('date created')

当我运行manage.py makemigrations时,出现以下错误:

You are trying to add a non-nullable field 'id' to world without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
 1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
 2) Quit, and let me add a default in models.py

为什么Django为什么认为我有一个id字段,以及如何摆脱这个错误?

1 个答案:

答案 0 :(得分:0)

我以前在我的世界模型中设置了一个ID字段,这使我感到有些困惑,因为我删除了它,并添加了以下行:

id = models.AutoField(primary_key=True)

当我再次运行makemitigrations时,它询问我是否将ID字段重命名为这个新字段,然后单击“是”并进行了排序。

我的模特现在是:

class World(models.Model):
    id = models.AutoField(primary_key=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default='')
    name = models.CharField(max_length=200)
    setting = models.CharField(max_length=200)
    creation_date = models.DateTimeField('date created')