3

尝试使用 Django 将数据插入到我的数据库中的表中。这是我要插入的表的模型:

class RunableFilters(models.Model):
    equipment_id = models.BigIntegerField(null=True, blank=True)
    filter_file_name = models.CharField(max_length=255, blank=True)
    last_updated = models.CharField(max_length=255, blank=True)
    class Meta:
        db_table = 'runable_filters'

我得到的错误:

>>> from books.models import RunableFilters
>>> p1 = RunableFilters(equipment_id = '123456778', filter_file_name = "test_file_name", last_updated = "2013-16-8")
>>> p1.save()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "C:\Python27\lib\site-packages\django\db\models\base.py", line 546, in save
    force_update=force_update, update_fields=update_fields)
  File "C:\Python27\lib\site-packages\django\db\models\base.py", line 650, in save_base
    result = manager._insert([self], fields=fields, return_id=update_pk, using=using, raw=raw)
  File "C:\Python27\lib\site-packages\django\db\models\manager.py", line 215, in _insert
    return insert_query(self.model, objs, fields, **kwargs)
  File "C:\Python27\lib\site-packages\django\db\models\query.py", line 1675, in insert_query
    return query.get_compiler(using=using).execute_sql(return_id)
  File "C:\Python27\lib\site-packages\django\db\models\sql\compiler.py", line 937, in execute_sql
    cursor.execute(sql, params)
  File "C:\Python27\lib\site-packages\django\db\backends\util.py", line 41, in execute
    return self.cursor.execute(sql, params)
  File "C:\Python27\lib\site-packages\django\db\backends\oracle\base.py", line 717, in execute
    six.reraise(utils.DatabaseError, utils.DatabaseError(*tuple(e.args)), sys.exc_info()[2])
  File "C:\Python27\lib\site-packages\django\db\backends\oracle\base.py", line 710, in execute
    return self.cursor.execute(query, self._param_generator(params))
DatabaseError: ORA-00904: "RUNABLE_FILTERS"."ID": invalid identifier

那是我数据库中的表

在此处输入图像描述

4

1 回答 1

4

这就是问题所在,django 需要一个名为的 PK 字段id

您可以轻松解决它,了解如何集成遗留数据库:https ://docs.djangoproject.com/en/dev/howto/legacy-databases/ 。

对于您的代码,找到主键并通知 django。让我们假设equipment_id可以充当pk:

class RunableFilters(models.Model):
    equipment_id = models.BigIntegerField( primary_key=True)  #<-- here
    filter_file_name = models.CharField(max_length=255,  ...

如果你有一个复合 pk,那么,请阅读这篇文章:https ://code.djangoproject.com/wiki/MultipleColumnPrimaryKeys

于 2013-08-19T16:52:04.867 回答