0

I want to run a command for the duration of the lifetime of the website. I don't want to run it more than once.

Let's say I want to run the query:

set names utf8mb4;

Then I would just run something like:

SomeRandomObject.objects.raw('set names utf8mb4;')

Where should I put this? Does it matter what object I run the query on? Is there a better object?

User
  • 23,729
  • 38
  • 124
  • 207

1 Answers1

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
  • 15,099
  • 2
  • 27
  • 47
  • I only have 1 database configuration specified in settings.py, so I suppose it's one connection? Also, what file did you put this in? – User Dec 19 '16 at 00:26
  • 1
    Yes, that is just one database. You can place this snippet wherever you want. It’s up to you how you call it. As suggested by Paul Collingwood, if you want this to run at startup, just put it in your views file outside of any views. – 2ps Dec 19 '16 at 01:45