Target database in raw query

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

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


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


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(….


Try the using() method.

Yes, thanks, that worked:

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

1 Like