Home > Enterprise >  Django get queryset fail on unmanaged database
Django get queryset fail on unmanaged database

Time:12-31

I'm trying to use Django's ORM on a read-only database.

Here is the model used:

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'

The configuration of the database part in the settings.py file :

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',
    }
}

And querysets :

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...
                                                             ^

Values :

'sql' => SELECT "languages"."idlanguage", "languages"."language", "languages"."code" FROM "languages" WHERE "languages"."idlanguage" = %s LIMIT 21
'params' => (1,)

Why the get queryset does not work ?

CodePudding user response:

You should put .using() first, since .get() resolves eagerly, and then it is thus "too late", so:

Languages.objects.using('ro_bdd').get(idlanguage=1)

A model object also has no .using(), so it would eventually result in a type error if the .get() was successful.

  • Related