Django执行migration的RunPython时提示'Object has no attribute'错误
错误原因
Django 迁移流程中通过apps.get_model()获取的是迁移快照版本的模型,仅包含对应时期的数据库字段属性,不会加载你在模型类中编写的自定义Python逻辑,包括@property装饰的计算属性、自定义方法等,因此调用user.is_two_fa_enabled时会抛出属性不存在的错误。
修复方法
直接使用数据库实际存储的two_fa_type字段做判断即可,修改迁移文件中的apply_func逻辑:
def apply_func(apps, schema_editor): User = apps.get_model("accounts", "User") for user in User.objects.all(): if user.two_fa_type: user.is_verified = True user.save()
如果你的用户量较大,可以使用批量更新方法优化性能,避免逐条遍历保存:
def apply_func(apps, schema_editor): User = apps.get_model("accounts", "User") User.objects.filter(two_fa_type__isnull=False).update(is_verified=True)
内容的提问来源于stack exchange,提问作者Sevy
相关产品推荐
相关产品推荐

