Django SQLite DB Cleanup
To beginners of Django, you may want to play with the sqlite db configuration commands before you actually implement something related to your project. The cleanup afterwards may be harmful due to the lack of clear instructions found online, and many cleanup should be done manually. Some useful commands and solutions to weird issues will be addressed.
DB Commands
Migrations
python manage.py makemigrations : creating new migrations based on the changes you have made to your models
python manage.py migrate : applying & unapplying migrations
- Issues
-
occur
- Run python manage.py migrate —fake instead
- Probably due to schema changes not synced with DB tables; check schema with python manage.py inspectdb
- Suggest cleaning up the entire database in the following section
- Dump all data in the DB: python manage.py flush :
find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
find . -path "*/migrations/*.pyc" -delete
: rm db.sqlite3 - Run migrations again
- sqlite3 db.sqlite : enter the sqlite3 shell
- >>> .schema : check schema
- Verify your schema. If not matched with models, identify the outdated table and proceed with the following steps; otherwise, there must be other problems.
- >>> drop table [table_name] : drop the table
- >>> create table [table_name] (. ); : create the table again manually with the updated fields :
find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
find . -path "*/migrations/*.pyc" -delete - Run migrations again
Clean Up
This is only used when you want to clean up the entire database, e.g. you're playing with your DB and wants to start implementing real things now.
Now all things should be reset.
Schema
Suppose now you already have a bunch of data and you really don't wanna dump them away. But after you modify the models, you found that the database schema won't be updated!
Here is the suggested way:
Now you can check schema with python manage.py inspectdb again, and the related model should be updated.
This might not be the most perfect solution, but I bet there is no other simple way to update the schema without dumping the database all away; at least after all of the research, this is the only effective way I found to solve my problem.
Clearing the database with Django commands
In a previous post, I presented a method of loading initial data into a Django database by using a custom management command. An accompanying task is cleaning the database up. Here I want to discuss a few options of doing that.
First, some general design notes on Django management commands. If you run manage.py help you’ll see a whole bunch of commands starting with sql. These all share a common idiom — print SQL statements to the standard output. Almost all DB engines have means to pipe commands from the standard input, so this plays great with the Unix philosophy of building pipes of single-task programs.
Django even provides a convenient shortcut for us to access the actual DB that’s being used with a given project — the dbshell command.
As an example, we have the sqlflush command, which returns a list of the SQL statements required to return all tables in the database to the state they were in just after they were installed. In a simple blog-like application with "post" and "tag" models, it may return something like:
Note there’s a lot of tables here, because the project also installed the admin and auth applications from django.contrib.
We can actually execute these SQL statements, and thus wipe out all the DB tables in our database, by running:
For this particular sequence, since it’s so useful, Django has a special built-in command named flush.
But there’s a problem with running flush that may or may not bother you, depending on what your goals are. It wipes out all tables, and this means authentication data as well. So if you’ve created a default admin user when jump-starting the application, you’ll have to re-create it now.
Perhaps there’s a more gentle way to delete just your app’s data, without messing with the other apps? Yes. In fact, I’m going to show a number of ways.
First, let’s see what other existing management commands have to offer. sqlclear will emit the commands needed to drop all tables in a given app. For example:
So we can use it to target a specific app, rather than using the kill-all approach of flush. There’s a catch, though. While flush runs delete to wipe all data from the tables, sqlclear removes the actual tables. So in order to be able to work with the database, these tables have to be re-created. Worry not, there’s a command for that:
So here’s a first way to do a DB cleanup: pipe sqlclear appname into dbshell. Then pipe sql appname to dbshell.
An alternative way, which I like less, is to take the subset of DELETE statements generated by sqlflush, save them in a text file, and pipe it through to dbshell when needed. For example, for the blog app discussed above, these statements should do it:
The reason I don’t like it is that it forces you to have explicit table names stored somewhere, which is a duplication of the existing models. If you happen to change some of your foreign keys, for example, tables will need changing so this file will have to be regenerated.
The approach I like best is more programmatic. Django’s model API is flexible and convenient, and we can just use it in a custom management command:
What is the easiest way to clear a database from the CLI with manage.py in Django?
I am using Django to build a website with MySQL. Now as I am learning so I need to change the Model very often so I want that all tables get cleared and new table get created.
But syncdb doesn’t touch existing tables. Is there any better way to handle this problem?
5 Answers 5
If you don’t care about data:
Best way would be to drop the database and run syncdb again. Or you can run:
(you can add —no-input to the end of the command for it to skip the interactive prompt.)
If you do care about data:
syncdb will only create tables for models which have not yet been installed. It will never issue ALTER TABLE statements to match changes made to a model class after installation. Changes to model classes and database schemas often involve some form of ambiguity and, in those cases, Django would have to guess at the correct changes to make. There is a risk that critical data would be lost in the process.
If you have made changes to a model and wish to alter the database tables to match, use the sql command to display the new SQL structure and compare that to your existing table schema to work out the changes.
Сбросить базу данных в Django

При работе с базами данных мы часто попадаем в ситуации, когда нам нужно сбросить всю базу данных. Возможными причинами могут быть добавление или удаление некоторых таблиц базы данных, изменения в дизайне базы данных, проблемы с логикой и связями, или база данных была заполнена слишком большим количеством бесполезных данных. В любом случае, Django действительно упрощает решение этой проблемы.
Более того, Django предоставляет нам несколько команд, которые могут справиться с этим за нас. Одна из этих команд может сбросить базу данных в Django, и мы здесь, чтобы продемонстрировать, как вы можете ее использовать.
Сбросить базу данных SQLite3 в Django
Если вы используете базу данных SQLite3 для своего проекта Django и вам необходимо ее сбросить, выполните следующие действия:
Удалите файл db.sqlite3 . Если этот файл содержит важные данные, вы можете создать для них резервную копию.
Удалите все папки migrations во всех приложениях Django.
Сделайте миграции для всех приложений Django с помощью команды python manage.py makemigrations . Могут быть случаи, когда миграции не выполняются для приложений; в этом случае добавьте имена приложений к этой команде, например python manage.py makemigrations MyAppOne MyAppTwo MyAppThree .
Наконец, перенесите миграции с помощью этой команды: python manage.py migrate .
Сбросить всю базу данных в Django
Если нам нужно полностью сбросить всю базу данных, мы будем использовать следующую команду: (Примечание: после использования этого кода все существующие суперпользователи также будут удалены.)
Сбросить таблицы базы данных приложения в Django
Если нам нужно удалить таблицы базы данных приложения Django, мы воспользуемся следующей командой. Следующий код отменяет все миграции для этого конкретного приложения:
Vaibhav is an artificial intelligence and cloud computing stan. He likes to build end-to-end full-stack web and mobile applications. Besides computer science and technology, he loves playing cricket and badminton, going on bike rides, and doodling.