Django – Finding out which database was used

I have a fairly complicated django app going that uses the same app models across multiple databases. Querysets have the .using() function which makes this fairly easy to deal with (except contenttypes…) but I ran into a situation today where I needed to go backwards from a model and find out which database it came from. I didn’t find any answers online or in irc, so I dug into some source and tracked down the _state.db attribute on models. Here is an example:


results = Model.objects.using('test_database').all()
results[0]._state.db
>>> test_database

Hopefully you find this quickly if you have the same question I had. :)

Leave a Comment