gpt4 book ai didi

Django 迁移无法将用户实例分配给用户字段

转载 作者:行者123 更新时间:2023-12-05 02:59:12 24 4
gpt4 key购买 nike

问题


最近我为 SubscriptionAccount 模型创建了一个新的迁移,它用指向 User 模型的链接替换了 email 字段。在此迁移中,我还进行了一次小型数据迁移,通过电子邮件获取用户并将其设置为 SubscriptionAccount.user。但是,出于某种原因,迁移不想将用户分配给新创建的 user 字段。提示它不能分配一个 User 实例 Ant ,它需要一个 User 实例。这很奇怪,因为这正是我正在做的。

错误


出现以下错误:

Traceback (most recent call last):
File "./manage.py", line 13, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python3.6/site-packages/django/core/management/__init__.py", line 356, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/usr/local/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python3.6/site-packages/django/core/management/commands/migrate.py", line 204, in handle
fake_initial=fake_initial,
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 115, in migrate
state = self._migrate_all_forwards(state, plan, full_plan, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 145, in _migrate_all_forwards
state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/executor.py", line 244, in apply_migration
state = migration.apply(state, schema_editor)
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/migration.py", line 126, in apply
operation.database_forwards(self.app_label, schema_editor, old_state, project_state)
File "/usr/local/lib/python3.6/site-packages/django/db/migrations/operations/special.py", line 193, in database_forwards
self.code(from_state.apps, schema_editor)
File "/project/hypernodedb/migrations/0069_link_subscription_account_to_user.py", line 26, in migrate_email_to_user
subscription_account.user = user
File "/usr/local/lib/python3.6/site-packages/django/db/models/fields/related_descriptors.py", line 220, in __set__
self.field.remote_field.model._meta.object_name,
ValueError: Cannot assign "<User: admin@example.com>": "SubscriptionAccount.user" must be a "User" instance.

我尝试了什么


我曾尝试将我获取的用户转换为实际的 User 实例,但无济于事。我做了很多调试,发现模块之间存在一些差异,发现在某些时候用户的模块被更改为 __fake__。然而,这只是在 Django 内部,所以我不确定那是什么。我检查了迁移中的所有类型,除了 __fake__ 模块外,一切似乎都井井有条。

我也尝试升级到最新的 django 和 DRF 版本,但这没有用。

代码


def migrate_email_to_user(apps, schema_editor):
SubscriptionAccount = apps.get_model('hypernodedb', 'SubscriptionAccount')
User = get_user_model()

for subscription_account in SubscriptionAccount.objects.all():
user, _ = User.objects.get_or_create(username=subscription_account.email)
subscription_account.user = user
subscription_account.save()


def revert_migrate_email_to_user(apps, schema_editor):
SubscriptionAccount = apps.get_model('hypernodedb', 'SubscriptionAccount')

for subscription_account in SubscriptionAccount.objects.all():
subscription_account.email = subscription_account.user.username
subscription_account.save()


class Migration(migrations.Migration):

dependencies = [
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
('hypernodedb', '0068_change_app_name_validation_error'),
]

operations = [
migrations.AddField(
model_name='subscriptionaccount',
name='user',
field=models.OneToOneField(null=True, default=None, on_delete=django.db.models.deletion.CASCADE,
to=settings.AUTH_USER_MODEL),
preserve_default=False,
),
migrations.RunPython(
code=migrate_email_to_user,
reverse_code=revert_migrate_email_to_user,
),
migrations.RemoveField(
model_name='subscriptionaccount',
name='email',
),
]

以下是迁移时的 SubscriptionAccount:

class SubscriptionAccount(TimeStampedModel):
user = models.OneToOneField(get_user_model(), null=True)
external_id = models.CharField(max_length=255)

def __str__(self):
return '{} - {}'.format(self.user.username, self.external_id)

这是更改前的模型:

class SubscriptionAccount(TimeStampedModel):
# TODO: link this to a user model in our auth system
email = models.CharField(max_length=255, unique=True)
external_id = models.CharField(max_length=255)

def __str__(self):
return '{} - {}'.format(self.user.username, self.external_id)

最佳答案

事实证明调用 get_user_model() 在迁移中使用不正确。如果你仔细想想,这是合乎逻辑的。因为您不应该直接在迁移中导入模型。然而,迁移错误让我失望了,提示它期待的是 User 而不是 User。此外,使用 get_user_model() 函数与直接导入函数略有不同(即,如果您使用不同的 User 模型会怎样)。

解决这个问题的方法是从 apps 导入 User 模型:

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

此后迁移顺利进行。

关于Django 迁移无法将用户实例分配给用户字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58219501/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com