Saperate每个客户端的PostgreSQL数据库,在单个Django应用程序和相同的服务器上创建客户端时自动迁移

2024-04-24 06:33:47 发布

您现在位置:Python中文网/ 问答频道 /正文

client_obj = Client.objects.create(name='client1')

status = create_database('client1')

def create_database('client1'):
    con = None
    dbname = 'client1'
    con = connect(dbname='postgres', user='***', host = 
    'localhost', password='***')
    con.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
    cur = con.cursor()
    cur.execute("SELECT 1 FROM pg_catalog.pg_database WHERE 
    datname = '{}' ".format(dbname))

    exists = cur.fetchone()
    if not exists:
        cur.execute('CREATE DATABASE ' + dbname)
        print "DATABASE NOT EXISTS"
    else:
        print "DATABASE EXISTS"

 cur.close()
 con.close()

创建数据库后,如何使迁移自动化?或者有其他方法来实现这一点吗?你知道吗


Tags: clientobjcloseexecutecreateexistscondatabase
1条回答
网友
1楼 · 发布于 2024-04-24 06:33:47
Instead of using:

cur.execute('CREATE DATABASE ' + dbname)

i have just create an empty database with initial migrations and now copying 
the same each time by using the command:

cur.execute('CREATE DATABASE {} WITH TEMPLATE created_db'.format(dbname))

now there no need of dynamic migrations to the newly created db.

相关问题 更多 >