7

我正在尝试迁移我的 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

有人知道我在做什么错吗?

4

4 回答 4

3

在这种情况下对我有什么帮助:

  1. 删除除__init__.py(/%prjname%/migrations 文件夹)以外的所有迁移文件
  2. python manage.py makemigrations
  3. python manage.py migrate

不确定确切原因,但我尝试使用由我的代码合作伙伴生成的文件,但没有成功。

于 2015-05-08T10:31:41.050 回答
3

好的,这是 Django 的另一个时髦特性,我花了好几个小时才弄明白。根据https://docs.djangoproject.com/en/1.8/topics/auth/customizing/#substituting-a-custom-user-model

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

所以要解决这个问题,最好的“干净”方法是将您的自定义用户模型创建放在 0001_initial.py 中,它会简单地工作。这就是Lebedev Sergey的 delete/makemigrations 技巧能够奏效的真正原因。

于 2015-09-22T22:55:41.473 回答
1

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

于 2016-02-16T15:24:07.810 回答
0

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

class MyModel(models.Model):  
    person = models.ForeignKey(settings.AUTH_USER_MODEL)
于 2014-02-07T12:18:18.393 回答