我正在尝试在只读数据库上使用Django的ORM。
下面是使用的模型:
class Languages(models.Model):
idlanguage = models.IntegerField(primary_key=True)
language = models.CharField(max_length=50)
code = models.CharField(max_length=50)
class Meta:
managed = False
db_table = 'languages'
settings.py文件中数据库部分的配置:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql',
'NAME': 'XXXXXXX',
'USER': 'XXX',
'PASSWORD': 'XXXXXXXXXXXXXXXXXXXXX',
'HOST': '',
'PORT': '',
},
'ro_bdd': {
'ENGINE': 'django.db.backends.oracle',
'NAME': 'XXXXX',
'USER': 'XXXXXXXXXX',
'PASSWORD': 'XXXXX',
'HOST': 'XXXXXXXXX',
'PORT': 'XXXX',
}
}
和查询集:
In [1]: Languages.objects.all().using("ro_bdd")
Out[1]: <QuerySet [<Languages: Languages object (1)>]>
In [2]: Languages.objects.filter(idlanguage=1).using("ro_bdd")
Out[2]: <QuerySet [<Languages: Languages object (1)>]>
In [3]: Languages.objects.get(idlanguage=1).using("ro_bdd")
/....../python3.9/site-packages/django/db/backends/utils.py in _execute(self, sql, params, *ignored_wrapper_args)
82 return self.cursor.execute(sql)
83 else:
---> 84 return self.cursor.execute(sql, params)
85
86 def _executemany(self, sql, param_list, *ignored_wrapper_args):
ProgrammingError: ERROR: relation « languages » does not exist
LINE 1: ..., "languages"."language", "languages"."code" FROM "languages...
^
价值观:
'sql' => SELECT "languages"."idlanguage", "languages"."language", "languages"."code" FROM "languages" WHERE "languages"."idlanguage" = %s LIMIT 21
'params' => (1,)
为什么get查询集不工作?
你应该把.using()
放在前面,因为.get()
解析很急切,然后它就"太迟了",所以:
Languages.objects.using('ro_bdd').get(idlanguage=1)
模型对象也没有.using()
,所以如果.get()
成功,最终会导致类型错误。