很多时候,我想应用一些自定义模式定义(函数、视图、类型、触发器、.)新数据库初始化时或测试运行之前。我在settings.py
中添加了以下内容,这是可行的
from django.db.models.signals import post_syncdb
from django.db import connection
# Apply schema changes not defined by Django. Set a module-level
# flag to guard against multiple invocations of syncdb_handler()
def syncdb_handler(**kwargs):
if getattr(connection, 'syncdb_called', None):
return
connection.syncdb_called = True
cursor = connection.cursor()
cursor.execute(open('/path/to/schema.sql')).read())
post_syncdb.connect(syncdb_handler)
这些文档似乎没有给出这样的解决方案。是否有将自定义SQL应用于数据库创建的约定?
在这个例子中,连接处理程序被多次调用,并且保持一个全局变量似乎不是一个好的设计模式。
发布于 2016-05-05 09:31:06
在过去,使用post_syncdb
信号是他做事情的首选方法(尽管将这些代码放在settings.py中是最不寻常的)。
但是syncdb不再被使用。现在数据库是用迁徙创建和修改的。使用migrations.RunSQL
或migrations.RunPython
对数据库进行自定义更改(如果需要)。
https://stackoverflow.com/questions/37056657
复制