使用现有数据库的django中的"未知列X.id"错误

ola*_*ndo 8 python django

我正在尝试为存在的数据库创建一个模型.使用输出manage.py inspectdb,我的models.py文件看起来像这样:

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'
Run Code Online (Sandbox Code Playgroud)

当我尝试这样做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'")
Run Code Online (Sandbox Code Playgroud)

为什么django认为应该有一个scripts.id专栏?如何在丢弃表等的情况下修复它?

ste*_*anw 14

默认情况下,默认情况下隐式id字段为每个模型上的自动递增主键.请参阅Django文档中的primary_key如何将该字段更改为其他名称,但需要有一个主键(也在您的表中).

此外,您可能不想调用其中一个字段super,因为它会super在类体中隐藏Python的内置.有一天你可能很难找到一个bug.