Django与外键用户迁移模型失败

我试图迁移我的Django模型:

from django.contrib.auth.models import User


class Post(models.Model):
    headline = models.CharField(max_length=200)
    slug = models.SlugField(max_length=200)
    body = models.TextField(blank=True, null=True)
    author = models.ForeignKey(User, null=True, blank=True)

我在创建模型后添加了作者字段。

这是django创建的迁移:

# encoding: utf8
from django.db import models, migrations


class Migration(migrations.Migration):

    dependencies = [('articles', '0002_auto')]

    operations = [
        migrations.AddField(
            field = models.ForeignKey(to_field=u'id', to=u'auth.User', blank=True, null=True),
            name = 'author',
            model_name = 'post',
        ),
    ]

当我尝试运行./manage.py migrate时,以下是我的回溯:

Operations to perform:
  Synchronize unmigrated apps: ckeditor, sessions, admin, messages, auth, staticfiles, contenttypes, django_extensions
  Apply all migrations: articles
Synchronizing apps without migrations:
  Creating tables...
  Installing custom SQL...
  Installing indexes...
Installed 0 object(s) from 0 fixture(s)
Running migrations:
  Applying articles.0002_post_author...Traceback (most recent call last):
  File "./manage.py", line 10, in <module>
    execute_from_command_line(sys.argv)
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/core/management/__init__.py", line 397, in execute_from_command_line
    utility.execute()
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/core/management/__init__.py", line 390, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/core/management/base.py", line 242, in run_from_argv
    self.execute(*args, **options.__dict__)
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/core/management/base.py", line 289, in execute
    output = self.handle(*args, **options)
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/core/management/commands/migrate.py", line 116, in handle
    executor.migrate(targets, plan, fake=options.get("fake", False))
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/migrations/executor.py", line 60, in migrate
    self.apply_migration(migration, fake=fake)
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/migrations/executor.py", line 73, in apply_migration
    migration.apply(project_state, schema_editor)
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/migrations/migration.py", line 80, in apply
    operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/migrations/operations/fields.py", line 22, in database_forwards
    schema_editor.add_field(from_model, to_model._meta.get_field_by_name(self.name)[0])
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/backends/schema.py", line 349, in add_field
    definition, params = self.column_sql(model, field, include_default=True)
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/backends/schema.py", line 105, in column_sql
    db_params = field.db_parameters(connection=self.connection)
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 1285, in db_parameters
    return {"type": self.db_type(connection), "check": []}
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 1276, in db_type
    rel_field = self.related_field
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 1183, in related_field
    return self.foreign_related_fields[0]
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 971, in foreign_related_fields
    return tuple(rhs_field for lhs_field, rhs_field in self.related_fields)
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 958, in related_fields
    self._related_fields = self.resolve_related_fields()
  File "/home/USER/.virtualenvs/PROJECT/src/django-trunk/django/db/models/fields/related.py", line 943, in resolve_related_fields
    raise ValueError('Related model %r cannot been resolved' % self.rel.to)
ValueError: Related model u'auth.User' cannot been resolved

任何人都知道我在做什么错了?


在这种情况下帮助我的是什么:

  • 删除__init__.py py(/%prjname%/ migrations文件夹)以外的所有迁移文件
  • python manage.py makemigrations
  • python manage.py migrate
  • 不知道确切的原因,但我试图使用由我的代码合作伙伴生成的文件,并没有解决。


    好吧,这是Django的另一个时髦功能,它花费我几个小时才能弄清楚。 根据https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#substotation-a-custom-user-model:

    由于Django对可交换模型的动态依赖特性的限制,您必须确保AUTH_USER_MODEL引用的模型是在其应用程序的第一次迁移 (通常称为0001_initial)中创建的; 否则,你将有依赖性问题。

    因此,要解决这个问题,最好的“干净”方法是将您的自定义用户模型创建在0001_initial.py中,并且它会很简单。 这就是列别杰夫谢尔盖的删除/制作技巧可以奏效的真正原因。


    如果您不使用自定义用户模型,这可能不是您的问题,但请记得始终使用get_user_model()或引用User类时。 另外,在定义外键时, settings.AUTH_USER_MODEL可以工作,如下所示:

    class MyModel(models.Model):  
        person = models.ForeignKey(settings.AUTH_USER_MODEL)
    
    链接地址: http://www.djcxy.com/p/73957.html

    上一篇: Django migrate model with user in a foreignkey fails

    下一篇: Issue in blocking user in chatlist using smack and open fire server