Target database in raw query

How does one target the database in a raw request, where you have a settings file like this:

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'db1',
        'USER': 'anotherluser',
        'PASSWORD': 'secr1t',
        'HOST': '127.0.0.1',
        'PORT': '3306'
    },
    'bl': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'bltest',
        'USER': 'luser',
        'PASSWORD': 'passw0rd',
        'HOST': '127.0.0.1',
        'PORT': '3306'
    }
}

Query:

theset = Bl.objects.raw(myquery, thevalues)

Model:

class Bl(models.Model):
    id = models.…

    class Meta:
        managed = False
        db_table = 'bl_pub'

I’ve done a fair amount of searching online, but all the examples seem to be like this:

from django.db import connections
cursor = connections['db_alias'].cursor()
cursor.execute("select * from my_table")

Rather than using Bl.objects.raw(….

Thanks

Try the using() method.

Yes, thanks, that worked:

theset = Bl.objects.using('bl').raw(myquery, thevalues)

1 Like