Django无法迁移 - 无法查询" peterson":必须是"用户"实例

时间:2017-07-21 13:23:57

标签: python django migration django-migrations

我在Django 1.9,Python 3.6上。我进行了此迁移,尝试为缺少它们的任何用户填写UserProfiles。

但我收到以下错误。

"用户"奇怪的是什么?变量似乎是一个用户实例。

from __future__ import unicode_literals
from django.db import migrations
from django.contrib.auth.models import User


def create_missing_profiles(apps, schema_editor):
    UserProfile = apps.get_model("myapp", "UserProfile")
    for user in User.objects.all():
        UserProfile.objects.get_or_create(user=user)


class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0004_auto_20170721_0908'),
    ]

    operations = [
        migrations.RunPython(create_missing_profiles),
    ]

错误:

ValueError:无法查询" peterson":必须是"用户"实例

1 个答案:

答案 0 :(得分:2)

看起来我只需要以与UserProfile相同的方式获取用户:

User = apps.get_model("auth", "User")

感谢@Daniel Roseman

完整的工作代码:

from __future__ import unicode_literals
from django.db import migrations


def create_missing_profiles(apps, schema_editor):
    UserProfile = apps.get_model("myapp", "UserProfile")
    User = apps.get_model("auth", "User")
    for user in User.objects.all():
        UserProfile.objects.get_or_create(user=user)


class Migration(migrations.Migration):

    dependencies = [
        ('myapp', '0004_auto_20170721_0908'),
    ]

    operations = [
        migrations.RunPython(create_missing_profiles),
    ]