You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.26 23:15:02