6

I would like to include some PostgreSQL functions as part of the database migration.

The two ways I can see are:

  1. Editing the migrations file (generated by python manage.py makemigrations)
  2. Hooking post table creation

The first seems easier, but laborious if the migration needs to be remade. What would you recommend the best way to go about it?

4
  • 2
    Why would the migration need to be remade? Commented Mar 5, 2019 at 16:13
  • 2
    You shouldn't edit migrations created by makemigrations, usually. But nothing stops you from adding your own migration (see here) with your own RunSQL commands, which will just be run as any other migration. Commented Mar 5, 2019 at 16:21
  • Thanks both.@RemcoGerlich in case the model is modified -- is there a better way to do that? @dirkgroten TIL I'll give that a go! Commented Mar 5, 2019 at 16:36
  • 1
    If a model is modified a new migration will be made, the old file won't be modified. I agree that this should be put in a new migration. Commented Mar 5, 2019 at 21:36

1 Answer 1

11

Answering my own question to clear up the question (thanks to all the comments):

First I made an empty migration (python manage.py makemigrations --empty app_name)

Then, to operations add the function's SQL:

migrations.RunSQL(
    ('CREATE OR REPLACE FUNCTION my_function() ...'),
    ('DROP FUNCTION IF EXISTS my_function();')
)

The two lines are for migrate and unmigrate SQL, read more here: https://docs.djangoproject.com/en/2.1/ref/migration-operations/#runsql

The custom migration will be run automatically after the main migrations.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.