在迁移期间防止生产服务器上 Django 应用程序中的 FieldDoesNotExist
Prevent FieldDoesNotExist in Django app on production server during migration
我运行在服务器上迁移是这样的:
- 上传 models.py 文件到服务器,其中包含一些新字段
sfield
im 模型 Mobject
- 在 manage.py
中执行 makemigration 命令
- 在 manage.py 中执行迁移命令
但是在第一步结束和第三步结束之间有一些请求因
django.core.exceptions.FieldDoesNotExist: Mobject has no field named 'sfield'
而失败(这很明显,因为 django ORM 无法从数据库中获取该字段但字段已经在 Class 中,所以 django 会尝试这样做)
是否可以完成所有 3 个步骤 "Atomic"?或者全局忽略此异常,因为现在我不需要 sfield
,我只想执行没有异常的迁移。或者我可以以某种方式临时标记新字段以防止 django 从数据库中获取它,但它必须对 makemigrations/migrate 可见?
如果你这样做 select * from yourtable
那么 django 会尝试获取模型中定义的所有字段。
您可以在您的 orms 中使用 only() 到 select 特定字段,这样在迁移 orm 中尚未使用的新字段时不会引发异常
顺便说一句,您应该在本地创建迁移文件,在本地计算机上测试新字段,然后将迁移文件提交到服务器。在服务器中部署时,部署后您只需要 migrate
,这样可以缩短发生异常的时间。
来自 django 文档:
The reason that there are separate commands to make and apply
migrations is because you’ll commit migrations to your version control
system and ship them with your app; they not only make your
development easier, they’re also useable by other developers and in
production.
我运行在服务器上迁移是这样的:
- 上传 models.py 文件到服务器,其中包含一些新字段
sfield
im 模型Mobject
- 在 manage.py 中执行 makemigration 命令
- 在 manage.py 中执行迁移命令
但是在第一步结束和第三步结束之间有一些请求因
django.core.exceptions.FieldDoesNotExist: Mobject has no field named 'sfield'
而失败(这很明显,因为 django ORM 无法从数据库中获取该字段但字段已经在 Class 中,所以 django 会尝试这样做)
是否可以完成所有 3 个步骤 "Atomic"?或者全局忽略此异常,因为现在我不需要 sfield
,我只想执行没有异常的迁移。或者我可以以某种方式临时标记新字段以防止 django 从数据库中获取它,但它必须对 makemigrations/migrate 可见?
如果你这样做 select * from yourtable
那么 django 会尝试获取模型中定义的所有字段。
您可以在您的 orms 中使用 only() 到 select 特定字段,这样在迁移 orm 中尚未使用的新字段时不会引发异常
顺便说一句,您应该在本地创建迁移文件,在本地计算机上测试新字段,然后将迁移文件提交到服务器。在服务器中部署时,部署后您只需要 migrate
,这样可以缩短发生异常的时间。
来自 django 文档:
The reason that there are separate commands to make and apply migrations is because you’ll commit migrations to your version control system and ship them with your app; they not only make your development easier, they’re also useable by other developers and in production.