Django, multiple databases with raw sql. How to choose db?

前端 未结 2 1681
情话喂你
情话喂你 2020-12-10 14:47

I have a Django project that utilizes multiple databases. https://docs.djangoproject.com/en/dev/topics/db/multi-db/

I perform a lot of raw queries like this:

相关标签:
2条回答
  • 2020-12-10 14:55

    try this may be it should works.

    from django.db import connections
    cursor = connections[’my_db_name’].cursor()
    # Your code here...
    transaction.commit_unless_managed(using=’my_db_name’)
    
    0 讨论(0)
  • 2020-12-10 15:19

    Refer django docs on executing custom query directly. Specify database in your connection as given below:

    from django.db import connections
    cursor = connections['db_alias'].cursor()
    cursor.execute("select * from my_table")
    

    And then commit using

    from django.db import transaction
    transaction.commit_unless_managed(using='db_alias')
    
    0 讨论(0)
提交回复
热议问题