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

无对应列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 都是必要的。

本文详细解释了在使用Django框架进行数据库迁移时遇到的“无对应列owner_id”错误,阐述了makemigrations和migrate两个命令的区别及正确用法,强调了两者在保持模型与数据库同步过程中的必要性。
4336

被折叠的 条评论
为什么被折叠?



