django-admin.py dumpdata to SQL statements

拈花ヽ惹草 提交于 2019-12-12 09:48:24

问题


I'm trying to dump my data to SQL statements. the django-admin.py dumpdata provides only json,xml,yaml. so:

  1. does someone know a good way to do it?!

  2. I tried that:

    def sqldumper(model):

    result = ""
    units = model.objects.all().values()
    for unit in units:
        statement = "INSERT INTO myapp.model "+str(tuple(unit.keys())).replace("'", "")+" VALUES " + str(tuple(unit.values()))+"\r\n"
        result+=statement
    return result
    

so I'm going over the model values myself, and make the INSERT statement myself. then I thought of using "django-admin.py sql" to get the "CREATE" statement.. but then I don't know how to use this line from inside my code (and not through the command-line). I tried os.popen and os.system, but it doesn't really work.. any tips about that?

I'll put it clearly: how do you use the "manage.py sql " from inside your code?

I add something like this to my view:

import os, sys
import imp
from django.core.management import execute_manager

sys_argv_backup = sys.argv
imp.find_module("settings")
import settings
sys.argv = ['','sql','myapp']
execute_manager(settings)
sys.argv = sys_argv_backup

the thing is - it works.. but it writes the statements to the stdout... it's something, but not perfect. I'll try using django.core.management.sql.sql_create directly, we'll see how it goes..

thanks


回答1:


I suggest to use SQL-specific dump program (e.g. mysqldump for MySQL).

For sqlite embedded in Python, you can look this example not involving Django:

# Convert file existing_db.db to SQL dump file dump.sql
import sqlite3, os

con = sqlite3.connect('existing_db.db')
with open('dump.sql', 'w') as f:
    for line in con.iterdump():
        f.write('%s\n' % line)


来源:https://stackoverflow.com/questions/5881194/django-admin-py-dumpdata-to-sql-statements

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!