[Fixed]-How do I run SQL queries after a DB connection is established?

1๐Ÿ‘

โœ…

I usually do this off the connection object itself.

from django.db import connections
cursor = connections['DATABASE_NAME'].cursor() 
# replace DATABASE_NAME with the name of your
# DATABASE connection, i.e., the appropriate key in the
# settings.DATABASES dictionary
cursor.execute("set names utf8mb4;")

This way you can avoid having to use some random model to run your raw queries.


n.b. if you only have one database connection, i.e., default you can use:

from django.db import connection
cursor = connection.cursor()
cursor.execute("set names utf8mb4;")

To run this once at startup, you can add the following to your DATABASES

DATABASES = {
    'default': {
        ...
        'OPTIONS': {
            "init_command": "set names utf8mb4;"
        }
    }
}
๐Ÿ‘ค2ps

Leave a comment