我在FK_Project
表中添加了新列rw_item
,这是Project_Master
表的引用。
dp=# ALTER TABLE digital_publisher_rw_item ADD FK_Project int;
ALTER TABLE
dp=# ALTER TABLE digital_publisher_rw_item ADD FOREIGN KEY(FK_Project) REFERENCES digital_publisher_project_master(id);
ALTER TABLE
现在我正在编写脚本以在FK_Project
表中添加列rw_item
的值。
但是得到以下异常,
异常:
>>> rw_item
<class 'dp.digital_publisher.models.rw_item'>
>>> rw_item.objects.all()
Traceback (most recent call last):
File "<console>", line 1, in <module>
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 67, in __repr__
data = list(self[:REPR_OUTPUT_SIZE + 1])
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 82, in __len__
self._result_cache.extend(self._iter)
File "/usr/lib/python2.6/site-packages/django/db/models/query.py", line 271, in iterator
for row in compiler.results_iter():
File "/usr/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 677, in results_iter
for rows in self.execute_sql(MULTI):
File "/usr/lib/python2.6/site-packages/django/db/models/sql/compiler.py", line 732, in execute_sql
cursor.execute(sql, params)
File "/usr/lib/python2.6/site-packages/django/db/backends/util.py", line 15, in execute
return self.cursor.execute(sql, params)
File "/usr/lib/python2.6/site-packages/django/db/backends/postgresql_psycopg2/base.py", line 44, in execute
return self.cursor.execute(query, args)
DatabaseError: column digital_publisher_rw_item.FK_Project_id does not exist
LINE 1: ..."digital_publisher_rw_item"."deletion_date_time", "digital_p...
^
Django models.py:
FK_Project = models.ForeignKey(Project_Master, null=True, blank=True)
如何处理?
答案 0 :(得分:1)
由于您要手动添加字段,而不是像王尚所指出的那样使用Django's database migrations,因此您只需确保字段名称匹配即可。在这种情况下,请注意Django给出的确切错误:
DatabaseError: column digital_publisher_rw_item.FK_Project_id does not exist
它正在寻找FK_Project_id
,而不是您添加的FK_Project
。这是因为Django中的一个约定,它将_id
追加到ForeignKey列的末尾。因此,您有两种处理方法:
重命名数据库中的列:ALTER TABLE digital_publisher_rw_item RENAME COLUMN FK_Project TO FK_Project_id
告诉Django使用您创建的列:FK_Project = models.ForeignKey(Project_Master, null=True, blank=True, db_column='FK_Project')