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

Gre*_*reg 4 python migration django 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),
    ]
Run Code Online (Sandbox Code Playgroud)

错误:

ValueError:无法查询“peterson”:必须是“User”实例。

Gre*_*reg 6

看起来我只需要像获取 UserProfile 一样获取 User:

User = apps.get_model("auth", "User")
Run Code Online (Sandbox Code Playgroud)

感谢@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),
    ]
Run Code Online (Sandbox Code Playgroud)