我正试图让这个'幻影'的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
之类的开关添加到字段定义中,那么它就会很棒,因此在构建测试数据库时它不会尝试生成列。但是,我认为目前不可能。
答案 0 :(得分:0)
实际上,你可以。只有它不是real
,而是abstract
,它适用于模型(但你应该能够使用继承来解决这个问题。)
你的模型结构可能需要一些按摩来对应Django所期望的,但这应该让你开始朝着正确的方向前进。