4

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 Answer 1

3

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)
Sign up to request clarification or add additional context in comments.

2 Comments

I thought about it, but let's say I'm using the ordinary sqlite3 that you get from django. I know it's easy on MySQL, but how do you do it on sqlite?
I added some "steps" I made to the question above, it's not perfect, but it's something to make me closer to the goal.. thanks though Don

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.