[Django]-How to get the database where a model instance was saved to in Django?

8👍

Use _state.db, as in:

my_obj = MyModel.objects.get(pk=1)
my_obj._state.db

This is shown in the routing example.

0👍

I believe you are looking for settings.py in the project (top level) Django directory. If not, would you post more information?

Here is a bit of my settings.py file in the Django project directory /home/amr/django/amr.

import os
DEBUG = True
TEMPLATE_DEBUG = DEBUG

ADMINS = (
    # ('Somone R. Somebody'so-forath-and-so-and-so@somewhere.com'),
)

MANAGERS = ADMINS

DATABASES = {
    'default': {
        #'ENGINE': 'django.db.backends.', # Add 'postgresql_psycopg2', 'postgresql', 'mysql', 'sqlite3' or 'oracle'.
        'ENGINE': 'mysql',
        'NAME': 'some-server-name',                      # Or path to database file if using sqlite3.
        'USER': '<user>',                      # Not used with sqlite3.
        'PASSWORD': 'xxxxxxxx',                  # Not used with sqlite3.
        'HOST': '',                      # Set to empty string for localhost. Not used with sqlite3.
        'PORT': '',                      # Set to empty string for default. Not used with sqlite3.
    }
}

SESSION_COOKIE_AGE = 15 * 60 * 60      # Age of cookie, in seconds

0👍

There is no way to directly get the info from a model instance itself. Ah, _state, yes. its You should explicitly pass in ‘using’ parameter, just like those built-in methods. Or design router which could deduce the DB to use by check some facts of the model instance, here the hunter.

👤okm

0👍

If you always save a model in the same db, you could store that info in model class and then use it when needed. Probably not very pythonic, but it may do the trick.

Class Hunter(models.Model):
    # ... other stuff
    db = 'hunter_db'

Access it then with __class__:

def add_ducks_to_hunt(hunter):
    db = hunter.__class__.db
    duck = Duck()
    duck.save(using=db)

On the other hand, if you save objects of one class in different databases, than I see no other way than to write each object’s id and db name at object’s save() to a table somewhere you can always access it and use that info to load the object.

👤frnhr

0👍

Assuming you have multiple databases, and you’ve defined a router, then you can just query your router like:

from myrouters import MyRouter
from myapp.models import Duck
using = MyRouter().db_for_write(Duck)
duck = Duck()
duck.save(using=using)

That said, I’m not sure why you’d need to do this. If the model exists on one database, and you’ve properly defined a router, then this should be unnecessary. Django will automatically lookup the correct default value for using. If the model exists on multiple databases simultaneously and want to control the specific database where it’s written to, then you should already know which database you want to use and shouldn’t need to query it.

👤Cerin

Leave a comment