django在model中添加字段報錯


在以下類中添加 description 字段后,

class Colors(models.Model):
    colors = models.CharField(u'顏色', max_length=10)
    description = models.CharField(u'描述', max_length=10)
    def __str__(self):
        return self.colors

 

執行以下初始化數據庫的步驟,報錯

C:\PycharmProjects\HelloWorld>python manage.py makemigrations
You are trying to add a non-nullable field 'description' to colors without a def
ault; 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
Select an option: 

這個可能是之前已創建了表中的一條記錄,之后模型中增加了一個非空的字段,但是原來已經存在的記錄沒有這個值

解決方案1:

修改字段為允許為空  null=True

class Colors(models.Model):
    colors = models.CharField(u'顏色', max_length=10)
    description = models.CharField(u'描述', max_length=10,null=True)
    def __str__(self):
        return self.colors

  

解決方案2:

先刪除整個migrations文件夾,再執行python manage.py makemigrations,和python manage.py migrate命令

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM