如何在django迁移中执行原始SQL [英] How do I execute raw SQL in a django migration
问题描述
一种方式:
我发现这样做的最好办法是使用RunSQL:
迁移包含RunSQL类。要执行此操作:
-
./ manage.py makemigrations --empty myApp
/ li>
- 编辑创建的迁移文件以包括:
operations =
migrations.RunSQL('RAW SQL CODE')
]
另一种方法
我最初解决问题的方法是使用 post_migrate
信号调用游标来执行我的原始SQL。
我必须添加到我的应用程序是这样的:
在 __ init __。py
myApp add:
default_app_config ='myApp.apps.MyAppConfig'
创建一个文件 apps.py
:
从django.apps导入AppConfig
从django.db.models.signals导入post_migrate
从myApp.db_partition_triggers导入create_partition_triggers
class MyAppConfig(AppConfig):
name ='myApp'
verbose_name =我的Ap p
def ready(self):
post_migrate.connect(create_partition_triggers,sender = self)
新文件 db_partition_triggers.py
:
from django.db import connection
def create_partition_triggers(** kwargs):
print'(re)为myApp创建分区触发器'
trigger_sql =CREATE OR REPLACE FUNCTION ...;如果不存在(...)CREATE TRIGGER ...
cursor = connection.cursor()
cursor.execute(trigger_sql)
print'完成创建分区触发器'
现在每个 manage.py syncdb
或 manage.py migrate
这个函数被调用,所以确保它使用 CREATE OR REPLACE
和如果不存在
,因此可以处理现有的功能。
I am aware of the cursor object in Django. Is there any other preferred way to execute raw SQL in migrations? I want to introduce postgresql partitioning for one of my models tables. The partition logic is a bunch of functions and triggers that have to be added to the database on setup which I'd like to automate.
One way:
The best way I found to do this is using RunSQL:
Migrations contains the RunSQL class. To do this:
./manage.py makemigrations --empty myApp
- edit the created migrations file to include:
operations = [
migrations.RunSQL('RAW SQL CODE')
]
Another way
The way I solved my problem initially was using the post_migrate
signal to call a cursor to execute my raw SQL.
What I had to add to my app was this:
in the __init__.py
of myApp add:
default_app_config = 'myApp.apps.MyAppConfig'
Create a file apps.py
:
from django.apps import AppConfig
from django.db.models.signals import post_migrate
from myApp.db_partition_triggers import create_partition_triggers
class MyAppConfig(AppConfig):
name = 'myApp'
verbose_name = "My App"
def ready(self):
post_migrate.connect(create_partition_triggers, sender=self)
New file db_partition_triggers.py
:
from django.db import connection
def create_partition_triggers(**kwargs):
print ' (re)creating partition triggers for myApp...'
trigger_sql = "CREATE OR REPLACE FUNCTION...; IF NOT EXISTS(...) CREATE TRIGGER..."
cursor = connection.cursor()
cursor.execute(trigger_sql)
print ' Done creating partition triggers.'
Now on every manage.py syncdb
or manage.py migrate
this function is called. So make sure it uses CREATE OR REPLACE
and IF NOT EXISTS
. So it can handle existing functions.
这篇关于如何在django迁移中执行原始SQL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!