Django在外键中用户迁移模型失败

时间:2013-09-03 21:05:46

标签: django migration django-users

我试图迁移我的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

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

3 个答案:

答案 0 :(得分:2)

好的,这是Django的另一个时髦功能,花了我几个小时来搞清楚。根据{{​​3}}:

  

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

因此,要解决此问题,最好的“干净”方法是将您的自定义用户模型创建放在0001_initial.py中,它就可以正常工作。这就是为什么https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#substituting-a-custom-user-model删除/ makemigrations技巧可以工作的真正原因。

答案 1 :(得分:1)

如果在应用任何其他迁移后进行此更改,则需要删除迁移文件夹中的所有其他内容,然后运行&#34; python manage.py makemigrations&#34;。那么你用于AUTH_USER_MODEL的任何东西都将是你的第一次迁移。

答案 2 :(得分:0)

如果您没有使用自定义用户模型,这可能不是您的问题,但请记住始终使用get_user_model()或引用User类时。此外,在定义外键时,settings.AUTH_USER_MODEL也适用,如:

class MyModel(models.Model):  
    person = models.ForeignKey(settings.AUTH_USER_MODEL)