sqlite3.OperationalError: no such column: **

最近在《phthon 从入门到实战》在第19章第三部分,按照要求在models.py(learning_logs app 里面的),添加了一行:owner=models.ForeignKey(User,on_delete=models.CASCADE),即添加了用户的一个外键,在执行了makemigrations 后,sunsever 时出现了一个错误,如下:

   sqlite3.OperationalError: no such column: **_第1张图片

无对应列owner_id,出现这个错误的原因是makemigrations 是告诉数据库添加了新列,但没有将改动应用于数据库,migrate则是将改动应用于数据库,关于makemigrations 和migrate 的区别,以下是摘自Moderator Chris Freeman的回答

"It is necessary to run both the commands to complete the migration of the database tables to be in sync with your models.

makemigrations simply analyzes your current models for any changes that would be out of sync with your database and creates a migrations file that can be used to bring the in sync. If left at this point, your models would still be out of sync with your database possibly breaking your code that queries the database.

migrate is the command to "Make It So!" and apply the changes noted during the makemigrations phase.

Applying [app] to either of these commands simply adds focus to that "app" and doesn't inspect all of your apps."

所以是忘了执行“migrate”,执行后错误消失。makemigrations、migrate 都是必要的。

你可能感兴趣的:(python,django,web)