Skip to content

Create and Run stored procedures

Sicong edited this page Aug 25, 2021 · 1 revision
  1. Create a stored procedure in migrations
    In yourapp/migrations create a custom migration file.
from django.db import migrations


class Migration(migrations.Migration):

    dependencies = [
        ('mytestapp', '0001_initial'),
    ]

    operations = [
        migrations.RunSQL("""CREATE PROCEDURE mySP
                             ...
                          """
       ),
    ]
$ python manage.py migrate
  1. The stored procedure can be called with a raw SQL query.
from django.db import connection

def run_mySP():
    with connection.cursor() as cursor:
        cursor.execute("EXEC mySP;")
        result = cursor.fetchall()
    return result 
Clone this wiki locally