我试图让这个“幻影”ForeignKey 引用一个模型,该模型是后端视图。该视图组装了包含来自原始表的一些数据的数据(因此它们共享一个主键)。
这是我们必须设置的简化版本(视图比模型更复杂,因此选择以这种方式设计)。
class VSpouse(models.Model):
person_id = models.IntegerField(primary_key=True)
...
class Person(models.Model):
person_id = models.AutoField(primary_key=True)
spouse = models.ForeignKey(VSpouse, db_column = 'person_id', to_field='person_id', null=True)
...
现在,由于表格是在模型之前在后端设计的,所以我们从未使用过syncdb
. 正因为如此,我们从未注意到任何问题,并且一切都按预期工作。
但是,现在我们开始开发一些 Django 测试,当它开始构建测试数据库时,我们看到以下内容:
$ python2 manage.py test misc --traceback
Creating test database for alias 'default'...
Destroying old test database 'default'...
Traceback (most recent call last):
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 222, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/lib/python2.7/site-packages/django/core/management/commands/test.py", line 72, in execute
super(Command, self).execute(*args, **options)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 255, in execute
output = self.handle(*args, **options)
File "/usr/lib/python2.7/site-packages/django/core/management/commands/test.py", line 89, in handle
failures = test_runner.run_tests(test_labels)
File "/usr/lib/python2.7/site-packages/django/test/simple.py", line 367, in run_tests
old_config = self.setup_databases()
File "/usr/lib/python2.7/site-packages/django/test/simple.py", line 315, in setup_databases
self.verbosity, autoclobber=not self.interactive)
File "/usr/lib/python2.7/site-packages/django/db/backends/creation.py", line 293, in create_test_db
load_initial_data=False)
File "/usr/lib/python2.7/site-packages/django/core/management/__init__.py", line 161, in call_command
return klass.execute(*args, **defaults)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 255, in execute
output = self.handle(*args, **options)
File "/usr/lib/python2.7/site-packages/django/core/management/base.py", line 385, in handle
return self.handle_noargs(**options)
File "/usr/lib/python2.7/site-packages/django/core/management/commands/syncdb.py", line 102, in handle_noargs
cursor.execute(statement)
File "/usr/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 58, in execute
six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
File "/usr/lib/python2.7/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 54, in execute
return self.cursor.execute(query, args)
DatabaseError: column "person_id" specified more than once
现在,我想我的问题是,是否有任何“正确”的方法可以做到这一点或解决这个问题?如果我可以real=False
在字段定义中添加一个类似的开关,那就太好了,这样它就不会在构建测试数据库时尝试生成列。但是,我认为目前不可能。