Django从SQLite3迁移至Oracle 11g遇ORA-2000错误:缺失ALWAYS关键字
Hey there! Let's break down why you're hitting this error when moving your Django app from SQLite3 to Oracle 11g. I've seen this exact issue a handful of times, and it all comes down to compatibility between Oracle 11g's limitations and how Django generates database schema by default.
问题根源
Oracle 11g doesn't support the IDENTITY column syntax—that feature was first introduced in Oracle 12c. When Django tries to run migrations for Oracle, if it's configured to use the newer 12c+ syntax (either due to a recent Django version or missing configuration), it will generate SQL that includes IDENTITY clauses with keywords like ALWAYS. Since 11g has no idea what this syntax means, you get the ORA-2000 error complaining about the missing ALWAYS keyword.
分步解决方法
1. 确认你的Django版本兼容Oracle 11g
Django 4.0 and above dropped support for Oracle 11g entirely. If you're using a newer Django version, you'll need to downgrade to a version that still supports 11g—Django 3.2 LTS is a solid pick here, as it's supported until 2024 and works seamlessly with Oracle 11g R2.
2. 调整数据库配置(settings.py)
Update your Oracle database settings to tell Django to use the older sequence-based auto-increment logic instead of the 12c+ IDENTITY columns. Add these options to your DATABASES config:
DATABASES = { 'default': { 'ENGINE': 'django.db.backends.oracle', 'NAME': 'your_oracle_service_name', # 例如 ORCL 'USER': 'your_db_username', 'PASSWORD': 'your_db_password', 'HOST': 'your_oracle_host', 'PORT': '1521', 'OPTIONS': { # 禁用11g不支持的returning_into特性 'use_returning_into': False, # 显式列出自增字段,让Django为其创建序列 'auto_increment_fields': ['id'], }, } }
3. 显式定义Model中的自增主键
虽然Django默认会自动创建id自增字段,但显式定义它能确保Django为Oracle 11g使用正确的序列逻辑。修改你的Model如下:
from django.db import models class YourModel(models.Model): # 显式声明自增主键 id = models.AutoField(primary_key=True) # 其他字段示例 name = models.CharField(max_length=100) description = models.TextField(null=True, blank=True) # ... 其余字段
4. 重新生成并执行迁移
首先,删除之前可能生成的、包含不兼容12c语法的迁移文件(查看你应用的migrations文件夹)。然后运行以下命令:
# 生成全新的迁移文件 python manage.py makemigrations # 将迁移应用到Oracle数据库 python manage.py migrate
额外检查点
- 确保你的Oracle客户端库版本与11g和Django版本兼容。
- 如果你使用了第三方Model字段,确认它们支持Oracle 11g(部分字段可能依赖12c+的特性)。
内容的提问来源于stack exchange,提问作者Mohamed Saleh

