【问题标题】:Django model force capitalizing db_column namesDjango 模型强制大写 db_column 名称
【发布时间】:2020-12-15 16:38:22
【问题描述】:

我正在创建一个从 Oracle SQL 数据库读取的 Django 模型。从模型读取的表中,一些列混合了大小写和空格,即“Region”和“Foo Bar”。所以

SELECT "Region", "Foo Bar" FROM some_table

在数据库方面完全有效。 Django 模型使用db_column 字段显式读取这些列,

class SomeModel(models.Model):
  region = models.CharField(max_length=100, db_column="Region")
  foo_bar = models.CharField(max_length=100, db_column="Foo Bar")

然而,当 Django 访问数据库时,我得到了错误

ORA-00904: invalid identifier: "some_table"."FOO BAR"

从列名在过程中的某处大写。有什么方法可以强制 Django 从 Django 的角度保留混合大小写,而无需修改 db 端的列名?

我尝试过:db_column="'Foo Bar'"'"Foo Bar"'"\"Foo Bar\"",这些似乎都没有使字符串按字面意思和大写字母解释。

谢谢!欢迎使用 Hacky 变通方法。

【问题讨论】:

  • 这闻起来像一个错误,特别是如果您查看 this test。你用的是什么版本?也许这在以后的版本中得到了修复。
  • 这似乎是 Oracle 的设计:see the code that does it

标签: python sql django oracle


【解决方案1】:

当使用 Oracle 数据库时,Django 将列名更改为大写 (see code)。

解决这个问题并不容易。您最好的选择可能是扩展 Oracle 以覆盖此功能。为此,您需要使用名为base.py 的文件为新后端创建一个模块。其内容如下所示:

from django.db.backends.oracle.base import DatabaseWrapper as OracleWrapper
from django.db.backends.oracle.operations import DatabaseOperations as OracleOperations

class DatabaseOperations(OracleOperations):
    def quote_name(self, name):
        # Modified version that doesn't apply upper to the quoted column names
        if not name.startswith('"') and not name.endswith('"'):
            name = '"%s"' % truncate_name(name.upper(), self.max_name_length())
        return name.replace('%', '%%')


class DatabaseWrapper(OracleWrapper):
    ops_class = DatabaseOperations

DatabaseWrapper 是一个特殊名称,您不应更改它。之后,您需要将模块设置为您的数据库引擎;您必须转到父模块(即,如果文件路径为myapp/backends/custom/base.py,则应将其设置为myapp.backends.custom)。

我没有时间正确测试这段代码(我实际上并没有 Oracle 数据库可以使用)但这是 GIS backends 的制作方式,所以它应该是相当安全的(但它可能需要一些其他东西)。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    • 2017-11-22
    相关资源
    最近更新 更多