【问题标题】:Django failing migration - Cannot query "peterson": Must be "User" instanceDjango 迁移失败 - 无法查询“peterson”:必须是“用户”实例
【发布时间】:2017-12-27 13:47:46
【问题描述】:

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

但我收到以下错误。

奇怪的是“用户”变量似乎是一个用户实例。

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”实例。

【问题讨论】:

  • 您也应该通过get_model 获取用户,而不是导入它。
  • 我想知道这一点。但是我该怎么称呼它呢?应用程序部分有什么? (也许将其作为答案提交?)
  • apps.get_model("auth", "User")。我没有将其作为答案提交,因为这不是您的问题的原因;但以后可能会导致其他问题。
  • 这实际上解决了我的问题。

标签: python django migration django-migrations


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-11-20
    • 2023-03-27
    • 2021-02-15
    • 1970-01-01
    • 2022-07-26
    • 2021-04-08
    • 2020-07-17
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多