Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: copy data from one database to another

I have two sqlite.db files. I'd like to copy the contents of one column in a table of on db file to another.

for example:

I have the model Information in db file called new.db:

class Information(models.Model):
        info_id = models.AutoField(primary_key = True)
        info_name = models.CharField( max_length = 50)

and the following information model in db file called old.db:

class Information(models.Model):
            info_id = models.AutoField(primary_key = True)
            info_type = models.CharField(max_length = 50)
            info_name = models.CharField( max_length = 50)

I'd like to copy all the data in column info_id and info_name from old.db to info_id and info_name in new.db.

I was thinking something like:

manage.py dbshell

then

INSERT INTO "new.Information" ("info_id", "info_name")
SELECT "info_id", "info_name"
FROM "old.Information";

This doesn't seem to be working. It says new.Information table does not exist... any ideas?

like image 684
JohnnyCash Avatar asked Jan 17 '23 00:01

JohnnyCash


1 Answers

You'd need to switch your database URL in your settings file to db2 and run syncdb to create the new tables. After that the easiest thing to do imo would be to switch back to db1 and run ./manage.py dumpdata myapp > data.json, followed by another switch to db2 where you can run ./manage.py loaddata data.json.

Afterwards, you can drop the data you don't need from db2.

Edit: Another approach would be to use the ATTACH function from sqlite. First, I recommend you do the first step above (change database settings and use syncdb to create the tables), then you can switch back and do this:

./manage.py dbshell

> ATTACH DATABASE 'new.db' AS newdb;
> INSERT INTO newdb.Information SELECT * FROM Information;
like image 57
Alex Vidal Avatar answered Jan 25 '23 07:01

Alex Vidal