Django 迁移失败 - 无法查询 "peterson":必须是 "User" 实例

Django failing migration - Cannot query "peterson": Must be "User" instance

我在 Django 1.9,Python 3.6。我进行此迁移是为了尝试为缺少用户配置文件的任何用户填写用户配置文件。

但我收到以下错误。

奇怪的是 "user" 变量似乎是一个 User 实例。

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": 必须是 "User" 个实例。

看来我只需要像获取 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),
    ]