Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I have a django application using multiple databases. Given an instance of a model, how can I obtain the database where it is stored (if any)? I need this to save another object to the same database as the first.

def add_ducks_to_hunt(hunter):
    db = # the hunter's db
    duck = Duck()
    duck.save(using=db)
like image 230
Juan Enrique Muñoz Zolotoochin Avatar asked Sep 17 '25 19:09

Juan Enrique Muñoz Zolotoochin


1 Answers

Use _state.db, as in:

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

This is shown in the routing example.

like image 123
Burhan Khalid Avatar answered Sep 19 '25 09:09

Burhan Khalid