Galaxy
Galaxy

Reputation: 2481

Can I arbitrarily replace and restore the db.sqlite3 file?

I know that the file db.sqlite3 in Django holds the entire database and the entire content within it. Is it safe to keep all the project files, the *.py files, the migrations files, but replace the db.sqlite3 file with a different one. If both these db.sqlite3 files work on the same database model, with the same tables, rows, columns, and everything, then if I swap out that file it should work seamlessly.

I want to copy the original db.sqlite3 file into a different directory. Then I want to create a new db.sqlite3 file in my project. Then I want to work with the new database file, and give it other data to test how the project would work with it. Then I want to delete the new db.sqlite3 file, and I want to restore the old one, which I've saved into another directory.

Would that work? And how can I create a new db.sqlite3 file, a clean state to put test data into?

Also, what if I build my project on another sever, can I copy my old db.sqlite3 file there too, and have the database with all it's saved data restored?

Basically, the main idea of my question is: are we to treat the db.sqlite3 file as a simple "text file" with input/output data for our program, something that is freely interchangeable?

Upvotes: 1

Views: 1395

Answers (2)

BoarGules
BoarGules

Reputation: 16952

The whole of the database lives in the .db file. You can safely copy it in either direction when there is no process running against the database. If there is a process running against the database then you might see rollback journal files or write-ahead log files in the same directory (if the database is in WAL mode) and if you leave these behind you might risk losing some pending transactions. Closing the database properly generally causes these files to disappear.

Upvotes: 3

Gasanov
Gasanov

Reputation: 3399

Yes, whole sqlite database is contained in one file, so you can freely move, replace, push it with django project (althought it's not recommended) and it will work fine.

Even if you have 2 different projects with same apps, same model structure and migrations, you can swap them.

If you remove your db.sqlite3 and want to create new one, just run python manage.py migrate and it will create new database and apply all migrations.

Upvotes: 1

Related Questions