首页 > 解决方案 > 当我没有时,Django 认为我有一个 id 字段

问题描述

我创建了以下模型:

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 字段,我该如何摆脱这个错误?

标签: djangopython-3.xsqlite

解决方案


我之前在我的 World 模型中设置了一个 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')

推荐阅读