【问题标题】:"Person.user" must be a "User" instance“Person.user”必须是“用户”实例
【发布时间】:2014-10-26 08:06:14
【问题描述】:

我正在编写一个小型数据迁移来为没有 UserProfiles 的现有 Django 用户创建 UserProfiles。

def forwards(self, orm):
    "Write your forwards methods here."
    for user in User.objects.all():
        try:
            person = user.get_profile()
        except:
            newperson = orm.Person(user=user)
            newperson.save()

但我不断得到

"Person.user" must be a "User" instance

我做错了什么?

【问题讨论】:

    标签: python django django-south


    【解决方案1】:

    在 South 中编写迁移时,您不必直接使用模型类,而是使用冻结的类。在上面的示例中,您可能试图将当前的 User 对象分配给冻结的 Person 对象。冻结的 Person 对象需要一个冻结的 User 对象。

    你需要改写如下:

    def forwards(self, orm):
        "Write your forwards methods here."
        for user in orm['auth.User'].objects.all():
            try:
                # cannot use user.get_profile() because it is not available in the frozen model
                person = orm.Person.get(user=user)  
            except:
                newperson = orm.Person(user=user)
                newperson.save()
    

    http://south.readthedocs.org/en/latest/ormfreezing.html#accessing-the-orm

    顺便说一句,我建议您不要使用裸露的 except,而是使用 except SomeException 来更健壮。

    【讨论】:

    • 我忘记了 django 的用户模型不在我的应用程序中。
    • 顺便说一句:现在我收到User object has no attribute 'get_profile' 为什么会这样?
    • 如果我在循环中打印user,我得到User Object 而不是[<User>: user] 左右。我想,这就是我收到上述错误的原因,对吧?
    • 是的,自定义模型方法没有冻结,您必须自己重新创建代码。请参阅south.readthedocs.org/en/latest/… 我现在正在更新我的答案。
    • 太棒了,我也刚刚读到这个:"The only caveat is that you won’t have access to any custom methods or managers on your models, as they’re not preserved as part of the freezing process (there’s no way to do this generally);"
    猜你喜欢
    • 1970-01-01
    • 2017-03-19
    • 1970-01-01
    • 1970-01-01
    • 2019-03-21
    • 2020-12-05
    • 2021-11-18
    • 2016-07-25
    • 1970-01-01
    相关资源
    最近更新 更多