使用多个数据库不存在 Django 错误关系 "auth_user"

Django error relation "auth_user" does not exist using multiple database

我正在使用多个数据库(同一 postgresql 数据库中的不同模式)开发 Django 1.9 和 python 3.3 项目。当我第一次尝试迁移项目时,出现此错误

Running migrations:
  Rendering model states... DONE
  Applying contenttypes.0001_initial... OK
  Applying auth.0001_initial... OK
  Applying MyApp.0001_initial...Traceback (most recent call last):
  File "/usr/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
psycopg2.ProgrammingError: ERROR:  relation "auth_user" does not exist


The above exception was the direct cause of the following exception:

Traceback (most recent call last):
  File "manage.py", line 10, in 
    execute_from_command_line(sys.argv)
  File "/usr/lib/python3.4/site-packages/django/core/management/__init__.py", line 350, in execute_from_command_line
    utility.execute()
  File "/usr/lib/python3.4/site-packages/django/core/management/__init__.py", line 342, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/usr/lib/python3.4/site-packages/django/core/management/base.py", line 348, in run_from_argv
    self.execute(*args, **cmd_options)
  File "/usr/lib/python3.4/site-packages/django/core/management/base.py", line 399, in execute
    output = self.handle(*args, **options)
  File "/usr/lib/python3.4/site-packages/django/core/management/commands/migrate.py", line 200, in handle
    executor.migrate(targets, plan, fake=fake, fake_initial=fake_initial)
  File "/usr/lib/python3.4/site-packages/django/db/migrations/executor.py", line 92, in migrate
    self._migrate_all_forwards(plan, full_plan, fake=fake, fake_initial=fake_initial)
  File "/usr/lib/python3.4/site-packages/django/db/migrations/executor.py", line 121, in _migrate_all_forwards
    state = self.apply_migration(state, migration, fake=fake, fake_initial=fake_initial)
  File "/usr/lib/python3.4/site-packages/django/db/migrations/executor.py", line 198, in apply_migration
    state = migration.apply(state, schema_editor)
  File "/usr/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 90, in __exit__
    self.execute(sql)
  File "/usr/lib/python3.4/site-packages/django/db/backends/base/schema.py", line 110, in execute
    cursor.execute(sql, params)
  File "/usr/lib/python3.4/site-packages/django/db/backends/utils.py", line 79, in execute
    return super(CursorDebugWrapper, self).execute(sql, params)
  File "/usr/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
  File "/usr/lib/python3.4/site-packages/django/db/utils.py", line 95, in __exit__
    six.reraise(dj_exc_type, dj_exc_value, traceback)
  File "/usr/lib/python3.4/site-packages/django/utils/six.py", line 685, in reraise
    raise value.with_traceback(tb)
  File "/usr/lib/python3.4/site-packages/django/db/backends/utils.py", line 64, in execute
    return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: ERROR:  relation "auth_user" does not exist

auth_user table 未迁移时,此错误似乎出现在其他项目中。在我的例子中,在迁移需要它的应用程序之前使用 manage.py migrate auth 开始我的迁移并不能解决问题。

我怀疑问题出在Django 中使用了不同的数据库。我的 auth_user table 存储在 默认数据库 并且 models.py 的内容被路由到其他数据库.

迁移过程是否在与我的应用程序数据库相同的数据库中查找 auth_user table?是完全不同的东西吗?

问题的答案

其实是跨库引用问题。 Django 无法创建跨数据库外键。

来自Django 1.8 documentation(并且在下一个版本中没有任何解决方案(当前版本是1.10)):

Cross-database relations

Django doesn’t currently provide any support for foreign key or many-to-many relationships spanning multiple databases. If you have used a router to partition models to different databases, any foreign key and many-to-many relationships defined by those models must be internal to a single database.

This is because of referential integrity. In order to maintain a relationship between two objects, Django needs to know that the primary key of the related object is valid. If the primary key is stored on a separate database, it’s not possible to easily evaluate the validity of a primary key.

If you’re using Postgres, Oracle, or MySQL with InnoDB, this is enforced at the database integrity level – database level key constraints prevent the creation of relations that can’t be validated.

However, if you’re using SQLite or MySQL with MyISAM tables, there is no enforced referential integrity; as a result, you may be able to ‘fake’ cross database foreign keys. However, this configuration is not officially supported by Django

如何解决和保持单独的数据库

在我的例子中,因为路由器正在工作,所以有一些技巧可以简化跨数据库对象。

class CrossDBUser(models.Model):
    user = models.IntegerField()

    def get_user(self):
        return User.objects.get(id=self.user)

    def set_user(self, user):
        self.user = user.id

class MyClassWithCrossDB(CrossDBUser):
    field1 = models.CharField(max_length=200, blank=False)
    field2 = models.IntegerField(default=0)

有了这个,我可以使用方法 set_userget_user 来处理存储在我的对象 MyClassWithCrossDB.

中的用户

当然它并不完美,因为它不允许像 on_delete=models.CASCADE 这样的自动操作,我不得不使用方法而不是实例变量。但这是解决方法。