将任何实例保存到数据库时,Django Oracle完整性错误

时间:2011-02-07 11:43:39

标签: sql django oracle django-models ora-01400

我正在从sqlite迁移到oracle后端。 oracle数据库已经存在并由其他人维护。它的版本是Oracle9i企业版9.2.0.1.0版。

我有一个简单的模型:

class AliasType(models.Model):
    id = models.AutoField(primary_key=True, db_column="F_ALIAS_ID")
    name = models.CharField(u"Type name", max_length=255, unique=True, db_column="F_ALIAS_NAME")

    class Meta:
        db_table = "ALIAS"

./manage.py syncdb不会返回任何错误。但是当我尝试创建一个新实例并将其保存到数据库时,我收到以下错误:

>>> AliasType.objects.create(name="test")
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/mnt/Data/private/projects/envs/termary-oracle/src/django/django/db/models/manager.py", line 138, in create
    return self.get_query_set().create(**kwargs)
  File "/mnt/Data/private/projects/envs/termary-oracle/src/django/django/db/models/query.py", line 360, in create
    obj.save(force_insert=True, using=self.db)
  File "/mnt/Data/private/projects/envs/termary-oracle/src/django/django/db/models/base.py", line 460, in save
    self.save_base(using=using, force_insert=force_insert, force_update=force_update)
  File "/mnt/Data/private/projects/envs/termary-oracle/src/django/django/db/models/base.py", line 553, in save_base
    result = manager._insert(values, return_id=update_pk, using=using)
  File "/mnt/Data/private/projects/envs/termary-oracle/src/django/django/db/models/manager.py", line 195, in _insert
    return insert_query(self.model, values, **kwargs)
  File "/mnt/Data/private/projects/envs/termary-oracle/src/django/django/db/models/query.py", line 1435, in insert_query
    return query.get_compiler(using=using).execute_sql(return_id)
  File "/mnt/Data/private/projects/envs/termary-oracle/src/django/django/db/models/sql/compiler.py", line 791, in execute_sql
    cursor = super(SQLInsertCompiler, self).execute_sql(None)
  File "/mnt/Data/private/projects/envs/termary-oracle/src/django/django/db/models/sql/compiler.py", line 735, in execute_sql
    cursor.execute(sql, params)
  File "/mnt/Data/private/projects/envs/termary-oracle/src/django/django/db/backends/util.py", line 18, in execute
    return self.cursor.execute(sql, params)
  File "/mnt/Data/private/projects/envs/termary-oracle/src/django/django/db/backends/oracle/base.py", line 630, in execute
    return self.cursor.execute(query, self._param_generator(params))
IntegrityError: ORA-01400: cannot insert NULL into ("SINCE"."ALIAS"."F_ALIAS_ID")

如果我指定了id,例如AliasType.objects.create(id=5, name="test"),它有效。我以为django应该能够自动检索id值。我已经知道Oracle不支持自动增量,我应该使用触发器和序列。我被告知数据库中存在一个返回所有新行的ID的现有序列,我知道它的名称,比如SEQ_GET_NEW_ID

所以问题是如何以最优雅的方式实现它,即如何告诉Django get id values for all new objects from the sequence named SEQ_GET_NEW_ID而不会过多地攻击它(例如覆盖所有模型的save()方法)?

1 个答案:

答案 0 :(得分:1)

打开一个故障单(#1946)以准确允许,覆盖默认序列名称。但由于它尚未关闭,我认为没有黑客攻击的方式。

之前我没有使用过Oracle,但快速搜索表明可以为序列创建别名/同义词。 manage.py sqlall <app>应该显示Django期望的序列名称。所以你可能只能将它作为SEQ_GET_NEW_ID的别名。