2010-11-16 18 views
7

我正在嘗試爲存在的數據庫創建模型。使用的manage.py inspectdb輸出,我models.py文件看起來像這樣:使用現有的數據庫在Django中出現「unknown column X.id」錯誤

from django.db import models 

...some more stuff here... 

class Scripts(models.Model): 
    run_site = models.ForeignKey(Sites, db_column='run_site') 
    script_name = models.CharField(max_length=120) 
    module_name = models.CharField(unique=True, max_length=120) 
    type = models.CharField(max_length=24) 
    cat_name = models.CharField(max_length=90) 
    owner = models.ForeignKey(QAPeople, db_column='owner') 
    only_server = models.CharField(max_length=120, blank=True) 
    guest = models.IntegerField() 
    registered = models.IntegerField() 
    super = models.IntegerField() 
    admin = models.IntegerField() 
    run_timing = models.CharField(max_length=27) 
    manual_owner = models.ForeignKey(QAPeople, db_column='manual_owner') 
    script_id = models.IntegerField(unique=True,) 
    version = models.IntegerField() 
    comment = models.ForeignKey('ScriptComments', null=True, blank=True) 
    class Meta: 
     db_table = u'scripts' 

當我嘗試做Scripts.objects.all()我得到

Traceback (most recent call last): 
    File "<console>", line 1, in <module> 
    File "C:\Python26\lib\site-packages\django\db\models\query.py", line 68, in __repr__ 
    data = list(self[:REPR_OUTPUT_SIZE + 1]) 
    File "C:\Python26\lib\site-packages\django\db\models\query.py", line 83, in __len__ 
    self._result_cache.extend(list(self._iter)) 
    File "C:\Python26\lib\site-packages\django\db\models\query.py", line 269, in iterator 
    for row in compiler.results_iter(): 
    File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py", line 672, in results_iter 
    for rows in self.execute_sql(MULTI): 
    File "C:\Python26\lib\site-packages\django\db\models\sql\compiler.py", line 727, in execute_sql 
    cursor.execute(sql, params) 
    File "C:\Python26\lib\site-packages\django\db\backends\util.py", line 15, in execute 
    return self.cursor.execute(sql, params) 
    File "C:\Python26\lib\site-packages\django\db\backends\mysql\base.py", line 86, in execute 
    return self.cursor.execute(query, args) 
    File "C:\Python26\lib\site-packages\MySQLdb\cursors.py", line 173, in execute 
    self.errorhandler(self, exc, value) 
    File "C:\Python26\lib\site-packages\MySQLdb\connections.py", line 36, in defaulterrorhandler 
    raise errorclass, errorvalue 
OperationalError: (1054, "Unknown column 'scripts.id' in 'field list'") 

爲什麼Django的認爲應該有一個scripts.id列?如何修復它沒有刪除表等?

回答

12

每個型號總是默認爲implicit id field as auto incrementing primary key。請參閱primary_key in the Django docs如何將該字段更改爲某個其他名稱,但需要有一個主鍵(也在您的表中)。

此外,您可能不想調用其中一個字段super,因爲它是在類體中隱藏Python的內置super。可能會讓你很難在某天找到bug。

+1

這就是爲什麼使用'model.pk'來引用主鍵而不是'model.id'是一個好習慣。 – 2010-11-16 18:02:55

0

我不知道,如果找你熟悉django-south?

這是一個不錯的小工具,可以幫助你從一個結構遷移到另一個數據也有助於commiting信息表之前確定問題,造成少錯誤和事後調試。

+0

此鏈接已損壞。這是新的:http://south.readthedocs.io/en/latest/ – 2016-08-09 21:31:29

相關問題