Search code examples
python-3.xdjangodjango-viewsmultiple-databases

In django, can the .using('db') keyword take a variable?


Example.objects.using('db').raw()

Instead of db could we have a variable that would correspond to the appropriate database?


Solution

  • Yes, you can.

    my_db = "default"
    
    Example.objects.using(my_db).get(pk=1)
    
    my_db = "other_db_key_from_DATABASES"
    
    Example.objects.using(my_db).get(pk=1)