Search code examples
djangomulti-database

How can I make a select in django using a multi-database?


I 'm using multi-database, and I try:

        cursor = connection.cursor().using(profile.dbname)
        cursor.execute('select id_retorno from prc_sequenciadora(' + str(profile.idempresa) + ', "VENDA_PEDIDO", "IDVENDA_PEDIDO", 0, 0)')# calls PROCEDURE named LOG_MESSAGE which resides in MY_UTIL Package
        cursor.fetchall()

But this error appears:

AttributeError at /comerx/pedidos/novo/ 'Cursor' object has no attribute 'using'

Here is traceback: http://pastebin.com/CD7B8BxJ

Thanks for all


Solution

  • First, you should import django.db.connections - which is a dictionary-like object that allows you to retrieve a specific database connection by its alias. Then you should use its appropriate cursor. I believe there is no "using" method for the Cursor object (that is what the error message says).

    So, we have:

    from django.db import connections
    my_db_alias = profile.dbname #in your situation
    cursor = connections[my_db_alias].cursor()
    # Your code goes here...
    

    For more information: https://docs.djangoproject.com/en/dev/topics/db/sql/#executing-custom-sql-directly