Skip to main content
 首页 » 编程设计

python之似乎无法丢失此错误 : "You are trying to add a non-nullable field"

2025年05月04日8kenshinobiy

无论我做什么,我似乎都无法在 django 模型中丢失此错误:

Did you rename twitterbot.bot to twitterbot.userbot (a ForeignKey)? [y/N] y 
You are trying to add a non-nullable field 'twitbot_id' to twitterbot 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) 
 2) Quit, and let me add a default in models.py 
Select an option: 2 

正如您在这里看到的,我已经根据文档正确设置了它,给出了一个“自动字段”。

那么是什么导致此错误持续存在?创建 Null = True/False 似乎没有任何改变。

class TwitterBot(models.Model): 
    twitbot_id = models.AutoField(primary_key=True) 
    userbot = models.ForeignKey(UserBot) 
    user_id = models.CharField(max_length=90, blank=True, null=True) 
    screenname = models.CharField(max_length=200, blank=True, null=True) 
    oauth_token = models.CharField(max_length=90, blank=True, null=True) 
    oauth_token_secret = models.CharField(max_length=90, blank=True, null=True) 
    hashtags = models.CharField(max_length=200, blank=True, null=True) 

请您参考如下方法:

Django 为每个模型添加一个默认的“id”字段,您不需要在模型中添加额外的“twitbot_id”。如果代理主键是您所需要的全部,请忘记“twitbot_id”,因为它将是自动生成的“id”的副本。参见 https://docs.djangoproject.com/en/dev/topics/db/models/#automatic-primary-key-fields

如果添加此项并且数据库中已有 TwitterBot 对象,则必须提供默认值来为数据库中的现有行填充此列。