【发布时间】: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