How to delete migrations django
How to delete migrations django
Resetting Django Migrations
The Django migration system was designed to deal with huge number of migrations. Typically you shouldn’t mind to keep a significant number of models migrations in your code base. However, you should keep in mind that it may cause certain unintended consequences, such taking considerable time when working with tests. But in circumstances like these you can simply deactivate the migrations.
If you like to make a clean-up, I will provide a few options in this guide.
When you need to modify your database structure but don’t want to or can’t remove a database table and recreate it, migrations may be quite useful. They are especially handy when you have a production database with tables that contain thousands of rows.
It’s not uncommon for a developer to be faced with the need to add, delete, or rename fields in an existing table. It’s possible to remove and re-create a table in certain instances, however consider a scenario where your application is already in production with thousands of database rows and you don’t have the option of deleting your old tables. Migrations are here to provide you with a more acceptable and competent solution since you can’t even bear to think about it.
Why using database migrations
In the case of a production database with tables containing huge amounts of rows, migrations are particularly useful because they allow you to propagate model changes to your database schema. They are particularly useful in the case of a need to change your database structure but you do not want or are unable to drop a database table and recreate it. Anyone who works with databases has come into instances in which he or she has had to make changes to the structure of an existing table by adding, removing, or renaming fields. Although it is possible to solve some problems by dropping the table and re-creating it, this will often result in the developer experiencing additional headaches as a result of the process. However, if your application is already in production and contains millions of database rows, dropping your old tables is not an option. As a result, migrations is here to give you a solution that is more acceptable and professional than what you are now contemplating.
Simply said, migrations allow you to modify the schema of your database while maintaining your data.
The good news is that these types of situations are rather common in the field of backend web development, and various valuable tools and techniques have been created to help developers deal with them effectively.
Because Django is a framework for building backend web applications, these challenges are typical for django developers, in which we need to reset the migrations and the database. When it comes to resetting migrations, we have many options:
Getting started with migrations
It is simple to get started with migrations, particularly with the most recent versions of Django, which begin with Django 1.7 and beyond. Due to the fact that migrations are incorporated into your Django web development process starting with version 1.7, they are now considered mandatory.
To be able to deal with migrations Django provides you with two important commands:
You can also show your migrations using the following command:
How to reset django migrations
Although the Django migrations system is extremely powerful, flexible, and designed to handle large numbers of migrations, having a large number of model migrations causes problems when frequently changing your database structure (which is most often the case during the development phase in most cases) to most django developers, both beginners and even experienced. If you find yourself in this circumstance, there is no other option except to clean up and reset the migrations. But how do you go about resetting Django migrations when things become truly out of hand?
The answer is straightforward, but it is dependent on whether you are still in the development phase or if you are in production, so let us go through the procedure step by step:
Reset Django migrations in development
So you’re still in the development phase of the application and it hasn’t gone into production. In this particular instance, removing the whole database is not a huge concern. Migrations may be reset in precisely three stages, which are as follows:
For those of you who are using sqlite, all you have to do is remove the sqlite3 file, which is usually titled db.sqlite3 when working with django.
This tiresome task may be easily automated if you are working from a command-line interface. As an example:
Make sure you have created a new database after deleting the old one if you are using any database system other than sqlite.
Deleting the database
Depending on the database system that is being utilized, you may be able to remove the actual database.
If you are working with MySQL, you must first establish a connection to your MySQL server using your command line:
You can also run the following command:
Then enter your password when MySQL prompts your for a password.
Next drop the MySQL database and create it again:
If you want to confirm if the database has been deleted before re-creating it again use the show command
psql will prompt you for a password, enter it and type Enter.
Now you can drop your database with
Then create it again
Reset Django migrations in production
That’s all there is to it for the first scenario, which is while you’re still developing your app and aren’t yet in production. Because you can’t dump your database while your app is in production, the process becomes more complicated. How do you reset migrations in this case?
In a nutshell, we need to maintain the database while removing the migration history from the system. Here is a step-by-step guide on how to do it:
Django will remove any prior migrations that were applied to the specified app (myApp).
It searches for Python files (migration files) in the migrations folder of each project app, with the exception of init.py, and deletes them.
The second line searches for Python files in the migrations folder of each project app except for init.py and deletes them.
You may quickly and easily check your migrations by utilizing the following command:
Don’t forget that the database still contains tables from the first migrations, so what we need to do is migrate our database while also mimicking the initial migrations, which can be accomplished by simply running the following command:
Using a Django app for resetting migrations
The following Django app, which was recently developed, allows you to reset migrations in a matter of minutes rather than going through all of the procedures above.
The app does all necessary actions, such as removing the migration files, clearing the django migrations database, and then recreating migrations and mimicking old migrations, as well as other tasks.
First, you need to install the app via pip:
Then, add the app in your INSTALLED_APPS under the settings.py file as follows:
Next, you can simply start using it from the CLI as follows:
You can also specify multiple apps for reset as follows:
Manually modifying the migrations
Given that migrations files are just Python scripts, you may want to consider manually updating your migrations to eliminate any potential problems in the future. Don’t be frightened of migrations; once you understand how they operate, they are really rather simple to handle. The Django documentation provides excellent explanations on how to write your own migrations.
Merging the migrations
There are occasions when just merging two or more migrations will resolve a problem; in this case, Django will prompt you to do so; however, this method is only effective for basic model updates.
When you appling your migrations, you should consider the following:
When Django detects that there are conflicts, it will prompt you to run the python manage.py makemigrations –merge command. In order to perform migrations simply follow the directions and run the command as follows:
Then, just migrate the database using the following command:
Unfortunately, this only works for simple modifications to your models.
Case 2 example: Dropping the database is not an option
Those are the only steps you need to do in cases when dumping the whole database is not a concern, which is only an option if you are just getting started on your project.
However, this is not always the case; in certain cases, you may not be able to simply delete a database because you want data for testing reasons throughout the development period or when in a production environment. What is the best way to reset your migrations without having them effect your real database?
When we wish to restart migrations, we don’t want to drop the database, therefore we use a workaround.
Clear or roll back database migrations
First start by clearing and rolling back migrations without touching the actual migration tables:
You need to replace appName with the actual app name and to do that for ach app you have in your project.
This command will un-apply all migration files for the specified app.
You can use showmigrations command to see all available migrations and to keep track of what you have cleared.
Remove migration files
After faking the migrations for all apps we need to delete the migrations files inside migrations folder in each app.
You can use the previous bash script to automate this process in Unix bases OSs.
This will delete Python source files and also compiled Python files for migrations except for the special Python file init.py
Make migrations again
Now you need to re-create the initial database migrations with the usual commands
Next you need to migrate your database again but since your database already exist, we didn’t delete them, remember?! with just need to fake the initial migrations using
If you run migrate without –fake or –fake-initial you are going to get this error:
So make sure to add the –fake-initial command switch.
Adding –fake switch marks migrations as run without actually running them.
Before following any process described above it’s advisable that you make sure you have no un-applied migrations before your proceed by running
You should get a message like this
Conclusion
So that brings us to the conclusion of this little tutorial; remember, migrations are nothing to be scared of. They are really useful, despite the fact that they may cause you some headaches. However, this is something that you will learn to handle as you get more Django expertise, as well as by understanding how migrations work so that you can avoid causing any conflicts while altering your models.
It’s possible that you’ll need to reset your Django migrations or just do a clean up at some point. This procedure may be completed quickly and simply in many circumstances, but it can get complicated if you have a large number of migration files and database tables to deal with. The options you learned in this article will allow you to essentially delete or reset your Django database migrations without having to worry about your project’s functionality being affected.
Documentation
Migrations¶
Migrations are Django’s way of propagating changes you make to your models (adding a field, deleting a model, etc.) into your database schema. They’re designed to be mostly automatic, but you’ll need to know when to make migrations, when to run them, and the common problems you might run into.
The Commands¶
There are several commands which you will use to interact with migrations and Django’s handling of database schema:
The migration files for each app live in a “migrations” directory inside of that app, and are designed to be committed to, and distributed as part of, its codebase. You should be making them once on your development machine and then running the same migrations on your colleagues’ machines, your staging machines, and eventually your production machines.
It is possible to override the name of the package which contains the migrations on a per-app basis by modifying the MIGRATION_MODULES setting.
Migrations will run the same way on the same dataset and produce consistent results, meaning that what you see in development and staging is, under the same circumstances, exactly what will happen in production.
Backend Support¶
Migrations are supported on all backends that Django ships with, as well as any third-party backends if they have programmed in support for schema alteration (done via the SchemaEditor class).
However, some databases are more capable than others when it comes to schema migrations; some of the caveats are covered below.
PostgreSQL¶
PostgreSQL is the most capable of all the databases here in terms of schema support.
MySQL¶
MySQL lacks support for transactions around schema alteration operations, meaning that if a migration fails to apply you will have to manually unpick the changes in order to try again (it’s impossible to roll back to an earlier point).
Finally, MySQL has relatively small limits on name lengths for columns, tables and indexes, as well as a limit on the combined size of all columns an index covers. This means that indexes that are possible on other backends will fail to be created under MySQL.
SQLite¶
SQLite has very little built-in schema alteration support, and so Django attempts to emulate it by:
This process generally works well, but it can be slow and occasionally buggy. It is not recommended that you run and migrate SQLite in a production environment unless you are very aware of the risks and its limitations; the support Django ships with is designed to allow developers to use SQLite on their local machines to develop less complex Django projects without the need for a full database.
Workflow¶
Once you have your new migration files, you should apply them to your database to make sure they work as expected:
Version control¶
Because migrations are stored in version control, you’ll occasionally come across situations where you and another developer have both committed a migration to the same app at the same time, resulting in two migrations with the same number.
Transactions¶
On databases that support DDL transactions (SQLite and PostgreSQL), all migration operations will run inside a single transaction by default. In contrast, if a database doesn’t support DDL transactions (e.g. MySQL, Oracle) then all operations will run without a transaction.
Dependencies¶
This means that when you run the migrations, the authors migration runs first and creates the table the ForeignKey references, and then the migration that makes the ForeignKey column runs afterward and creates the constraint. If this didn’t happen, the migration would try to create the ForeignKey column without the table it’s referencing existing and your database would throw an error.
This dependency behavior affects most migration operations where you restrict to a single app. Restricting to a single app (either in makemigrations or migrate ) is a best-efforts promise, and not a guarantee; any other apps that need to be used to get dependencies correct will be.
Migration files¶
Migrations are stored as an on-disk format, referred to here as “migration files”. These files are actually normal Python files with an agreed-upon object layout, written in a declarative style.
A basic migration file looks like this:
The operations are the key; they are a set of declarative instructions which tell Django what schema changes need to be made. Django scans them and builds an in-memory representation of all of the schema changes to all apps, and uses this to generate the SQL which makes the schema changes.
You should rarely, if ever, need to edit migration files by hand, but it’s entirely possible to write them manually if you need to. Some of the more complex operations are not autodetectable and are only available via a hand-written migration, so don’t be scared about editing them if you have to.
Custom fields¶
Model managers¶
You can optionally serialize managers into migrations and have them available in RunPython operations. This is done by defining a use_in_migrations attribute on the manager class:
If you are using the from_queryset() function to dynamically generate a manager class, you need to inherit from the generated class to make it importable:
Please refer to the notes about Historical models in migrations to see the implications that come along.
Initial migrations¶
The “initial migrations” for an app are the migrations that create the first version of that app’s tables. Usually an app will have one initial migration, but in some cases of complex model interdependencies it may have two or more.
Initial migrations are marked with an initial = True class attribute on the migration class. If an initial class attribute isn’t found, a migration will be considered “initial” if it is the first migration in the app (i.e. if it has no dependencies on any other migration in the same app).
History consistency¶
As previously discussed, you may need to linearize migrations manually when two development branches are joined. While editing migration dependencies, you can inadvertently create an inconsistent history state where a migration has been applied but some of its dependencies haven’t. This is a strong indication that the dependencies are incorrect, so Django will refuse to run migrations or make new migrations until it’s fixed. When using multiple databases, you can use the allow_migrate() method of database routers to control which databases makemigrations checks for consistent history.
Adding migrations to apps¶
New apps come preconfigured to accept migrations, and so you can add migrations by running makemigrations once you’ve made some changes.
If your app already has models and database tables, and doesn’t have migrations yet (for example, you created it against a previous Django version), you’ll need to convert it to use migrations by running:
Note that this only works given two things:
Reversing migrations¶
Migrations can be reversed with migrate by passing the number of the previous migration. For example, to reverse migration books.0003 :
If you want to reverse all migrations applied for an app, use the name zero :
A migration is irreversible if it contains any irreversible operations. Attempting to reverse such migrations will raise IrreversibleError :
Historical models¶
When you run migrations, Django is working from historical versions of your models stored in the migration files. If you write Python code using the RunPython operation, or if you have allow_migrate methods on your database routers, you need to use these historical model versions rather than importing them directly.
If you import models directly rather than using the historical models, your migrations may work initially but will fail in the future when you try to rerun old migrations (commonly, when you set up a new installation and run through all the migrations to set up the database).
This means that historical model problems may not be immediately obvious. If you run into this kind of failure, it’s OK to edit the migration to use the historical models rather than direct imports and commit those changes.
Because it’s impossible to serialize arbitrary Python code, these historical models will not have any custom methods that you have defined. They will, however, have the same fields, relationships, managers (limited to those with use_in_migrations = True ) and Meta options (also versioned, so they may be different from your current ones).
This means that you will NOT have custom save() methods called on objects when you access them in migrations, and you will NOT have any custom constructors or instance methods. Plan appropriately!
References to functions in field options such as upload_to and limit_choices_to and model manager declarations with managers having use_in_migrations = True are serialized in migrations, so the functions and classes will need to be kept around for as long as there is a migration referencing them. Any custom model fields will also need to be kept, since these are imported directly by migrations.
In addition, the concrete base classes of the model are stored as pointers, so you must always keep base classes around for as long as there is a migration that contains a reference to them. On the plus side, methods and managers from these base classes inherit normally, so if you absolutely need access to these you can opt to move them into a superclass.
To remove old references, you can squash migrations or, if there aren’t many references, copy them into the migration files.
Considerations when removing model fields¶
Similar to the “references to historical functions” considerations described in the previous section, removing custom model fields from your project or third-party app will cause a problem if they are referenced in old migrations.
Add the system_check_deprecated_details attribute to your model field similar to the following:
After a deprecation period of your choosing (two or three feature releases for fields in Django itself), change the system_check_deprecated_details attribute to system_check_removed_details and update the dictionary similar to:
Data Migrations¶
As well as changing the database schema, you can also use migrations to change the data in the database itself, in conjunction with the schema if you want.
Migrations that alter data are usually called “data migrations”; they’re best written as separate migrations, sitting alongside your schema migrations.
To start, make an empty migration file you can work from (Django will put the file in the right place, suggest a name, and add dependencies for you):
Then, open up the file; it should look something like this:
Let’s write a migration that populates our new name field with the combined values of first_name and last_name (we’ve come to our senses and realized that not everyone has first and last names). All we need to do is use the historical model and iterate over the rows:
Once that’s done, we can run python manage.py migrate as normal and the data migration will run in place alongside other migrations.
You can pass a second callable to RunPython to run whatever logic you want executed when migrating backwards. If this callable is omitted, migrating backwards will raise an exception.
Accessing models from other apps¶
More advanced migrations¶
Squashing migrations¶
You are encouraged to make migrations freely and not worry about how many you have; the migration code is optimized to deal with hundreds at a time without much slowdown. However, eventually you will want to move back from having several hundred migrations to just a few, and that’s where squashing comes in.
Squashing is the act of reducing an existing set of many migrations down to one (or sometimes a few) migrations which still represent the same changes.
These files are marked to say they replace the previously-squashed migrations, so they can coexist with the old migration files, and Django will intelligently switch between them depending where you are in the history. If you’re still part-way through the set of migrations that you squashed, it will keep using them until it hits the end and then switch to the squashed history, while new installs will use the new squashed migration and skip all the old ones.
This enables you to squash and not mess up systems currently in production that aren’t fully up-to-date yet. The recommended process is to squash, keeping the old files, commit and release, wait until all systems are upgraded with the new release (or if you’re a third-party project, ensure your users upgrade releases in order without skipping any), and then remove the old files, commit and do a second release.
Once you’ve squashed your migration, you should then commit it alongside the migrations it replaces and distribute this change to all running instances of your application, making sure that they run migrate to store the change in their database.
You must then transition the squashed migration to a normal migration by:
Once you’ve squashed a migration, you should not then re-squash that squashed migration until you have fully transitioned it to a normal migration.
Pruning references to deleted migrations
Serializing values¶
Django can serialize the following:
Django cannot serialize:
Custom serializers¶
You can serialize other types by writing a custom serializer. For example, if Django didn’t serialize Decimal by default, you could do this:
The first argument of MigrationWriter.register_serializer() is a type or iterable of types that should use the serializer.
The serialize() method of your serializer must return a string of how the value should appear in migrations and a set of any imports that are needed in the migration.
Adding a deconstruct() method¶
You can let Django serialize your own custom class instances by giving the class a deconstruct() method. It takes no arguments, and should return a tuple of three things (path, args, kwargs) :
This return value is different from the deconstruct() method for custom fields which returns a tuple of four items.
Django will write out the value as an instantiation of your class with the given arguments, similar to the way it writes out references to Django fields.
To prevent a new migration from being created each time makemigrations is run, you should also add a __eq__() method to the decorated class. This function will be called by Django’s migration framework to detect changes between states.
As long as all of the arguments to your class’ constructor are themselves serializable, you can use the @deconstructible class decorator from django.utils.deconstruct to add the deconstruct() method:
The decorator adds logic to capture and preserve the arguments on their way into your constructor, and then returns those arguments exactly when deconstruct() is called.
Supporting multiple Django versions¶
If you are the maintainer of a third-party app with models, you may need to ship migrations that support multiple Django versions. In this case, you should always run makemigrations with the lowest Django version you wish to support.
The migrations system will maintain backwards-compatibility according to the same policy as the rest of Django, so migration files generated on Django X.Y should run unchanged on Django X.Y+1. The migrations system does not promise forwards-compatibility, however. New features may be added, and migration files generated with newer versions of Django may not work on older versions.
The Migrations Operations Reference Covers the schema operations API, special operations, and writing your own operations. The Writing Migrations “how-to” Explains how to structure and write database migrations for different scenarios you might encounter.
How to delete migrations django
The Django migration system was developed and optmized to work with large number of migrations. Generally you shouldn’t mind to keep a big amount of models migrations in your code base. Even though sometimes it causes some undesired effects, like consuming much time while running the tests. But in scenarios like this you can easily disable the migrations (although there is no built-in option for that at the moment).
Anyway, if you want to perform a clean-up, I will present a few options in this tutorial.
Scenario 1:
The project is still in the development environment and you want to perform a full clean up. You don’t mind throwing the whole database away.
1. Remove the all migrations files within your project
Go through each of your projects apps migration folder and remove everything inside, except the __init__.py file.
Or if you are using a unix-like OS you can run the following script (inside your project dir):
2. Drop the current database, or delete the db.sqlite3 if it is your case.
3. Create the initial migrations and generate the database schema:
And you are good to go.
Scenario 2:
You want to clear all the migration history but you want to keep the existing database.
1. Make sure your models fits the current database schema
The easiest way to do it is trying to create new migrations:
If there are any pending migration, apply them first.
If you see the message:
You are good to go.
2. Clear the migration history for each app
Now you will need to clear the migration history app by app.
First run the showmigrations command so we can keep track of what is going on:
Clear the migration history (please note that core is the name of my app):
The result will be something like this:
Now run the command showmigrations again:
You must do that for all the apps you want to reset the migration history.
3. Remove the actual migration files.
Go through each of your projects apps migration folder and remove everything inside, except for the __init__.py file.
Or if you are using a unix-like OS you can run the following script (inside your project dir):
PS: The example above will remove all the migrations file inside your project.
Run the showmigrations again:
4. Create the initial migrations
5. Fake the initial migration
In this case you won’t be able to apply the initial migration because the database table already exists. What we want to do is to fake this migration instead:
Documentation
Migration Operations¶
Migration files are composed of one or more Operation s, objects that declaratively record what the migration should do to your database.
Django also uses these Operation objects to work out what your models looked like historically, and to calculate what changes you’ve made to your models since the last migration so it can automatically write your migrations; that’s why they’re declarative, as it means Django can easily load them all into memory and run through them without touching the database to work out what your project should look like.
There are also more specialized Operation objects which are for things like data migrations and for advanced manual database manipulation. You can also write your own Operation classes if you want to encapsulate a custom change you commonly make.
All of the core Django operations are available from the django.db.migrations.operations module.
Schema Operations¶
CreateModel ¶
Creates a new model in the project history and a corresponding table in the database to match it.
name is the model name, as would be written in the models.py file.
options is an optional dictionary of values from the model’s Meta class.
DeleteModel ¶
Deletes the model from the project history and its table from the database.
RenameModel ¶
Renames the model from an old name to a new one.
You may have to manually add this if you change the model’s name and quite a few of its fields at once; to the autodetector, this will look like you deleted a model with the old name and added a new one with a different name, and the migration it creates will lose any data in the old table.
AlterModelTable ¶
Changes the model’s table name (the db_table option on the Meta subclass).
AlterUniqueTogether ¶
Changes the model’s set of unique constraints (the unique_together option on the Meta subclass).
AlterIndexTogether ¶
Changes the model’s set of custom indexes (the index_together option on the Meta subclass).
AlterOrderWithRespectTo ¶
Makes or deletes the _order column needed for the order_with_respect_to option on the Meta subclass.
AlterModelOptions ¶
AlterModelManagers ¶
Alters the managers that are available during migrations.
AddField ¶
On older databases, adding a field with a default value may cause a full rewrite of the table. This happens even for nullable fields and may have a negative performance impact. To avoid that, the following steps should be taken.
RemoveField ¶
Removes a field from a model.
Bear in mind that when reversed, this is actually adding a field to a model. The operation is reversible (apart from any data loss, which is irreversible) if the field is nullable or if it has a default value that can be used to populate the recreated column. If the field is not nullable and does not have a default value, the operation is irreversible.
AlterField ¶
RenameField ¶
Changes a field’s name (and, unless db_column is set, its column name).
AddIndex ¶
RemoveIndex ¶
AddConstraint ¶
RemoveConstraint ¶
Special Operations¶
RunSQL ¶
If you want to include literal percent signs in the query, you have to double them if you are passing parameters.
The reverse_sql queries are executed when the migration is unapplied. They should undo what is done by the sql queries. For example, to undo the above insertion with a deletion:
If reverse_sql is None (the default), the RunSQL operation is irreversible.
The optional hints argument will be passed as **hints to the allow_migrate() method of database routers to assist them in making routing decisions. See Hints for more details on database hints.
Pass the RunSQL.noop attribute to sql or reverse_sql when you want the operation not to do anything in the given direction. This is especially useful in making the operation reversible.
RunPython ¶
The reverse_code argument is called when unapplying migrations. This callable should undo what is done in the code callable so that the migration is reversible. If reverse_code is None (the default), the RunPython operation is irreversible.
The optional hints argument will be passed as **hints to the allow_migrate() method of database routers to assist them in making a routing decision. See Hints for more details on database hints.
By default, RunPython will run its contents inside a transaction on databases that do not support DDL transactions (for example, MySQL and Oracle). This should be safe, but may cause a crash if you attempt to use the schema_editor provided on these backends; in this case, pass atomic=False to the RunPython operation.
If you have a different database and aren’t sure if it supports DDL transactions, check the django.db.connection.features.can_rollback_ddl attribute.
Pass the RunPython.noop method to code or reverse_code when you want the operation not to do anything in the given direction. This is especially useful in making the operation reversible.
SeparateDatabaseAndState ¶
A highly specialized operation that lets you mix and match the database (schema-changing) and state (autodetector-powering) aspects of operations.
It accepts two lists of operations. When asked to apply state, it will use the state_operations list (this is a generalized version of RunSQL ’s state_operations argument). When asked to apply changes to the database, it will use the database_operations list.
Writing your own¶
Operations have a relatively simple API, and they’re designed so that you can easily write your own to supplement the built-in Django ones. The basic structure of an Operation looks like this:
The migration_name_fragment property was added.
Some things to note:
You don’t need to learn too much about ProjectState to write migrations; just know that it has an apps property that gives access to an app registry (which you can then call get_model on).
database_forwards and database_backwards both get two states passed to them; these represent the difference the state_forwards method would have applied, but are given to you for convenience and speed reasons.
to_state in the database_backwards method is the older state; that is, the one that will be the current state once the migration has finished reversing.
You might see implementations of references_model on the built-in operations; this is part of the autodetection code and does not matter for custom operations.
As an example, let’s make an operation that loads PostgreSQL extensions (which contain some of PostgreSQL’s more exciting features). Since there’s no model state changes, all it does is run one command:
How Do I Reset Django Migration
Django Migrations: Reset, Remove, Delete applied migrations and its folder.
In this tutorial, you will learn about resetting Django applied migrations and creating fresh migrations.
NOTE: Whenever you reset migrations, you should first backup your database and migrations files and keep it in a safe place so that you can restore it later. Many times resetting migrations does not work as we expect because of the database complexity and we can loose the data.
Let’s discuss the two scenarios for which you might want to reset the migrations.
Scenario 1: Reset migrations by dropping the database
Remove all migrations files within your project. Go through each of your project’s apps migration folders and remove everything inside, except the __init__.py file.
In Linux based system, you can open your terminal and change your directory to the root of the project where manage.py is located and run these to remove all migration files.
The next step is to drop the current database:
Once DB is dropped and recreated, create the initial migrations and generate the database schema using
That’s all, it will apply to all the migrations. You can check out other django-tutorials
Scenario 2: Reset migrations without dropping database
This is useful and ideal for resetting migration for large apps where you have a big database. Make sure your models fit the current database schema. The easiest way to do it is by trying to create new migrations:
If there are any pending migrations, apply them first. If you see the below message, You are good to go.
Now you will need to clear the migration history app by app. First, run the showmigrations command so we can keep track of what is going on:
Clear the migration history (please note that core is the name of my app)
The result will be something like this:
Now run the command python manage.py showmigrations again
You must do that for all the apps you want to reset the migration history.
Now, remove the actual migration files. Go through each of your project’s app migration folders and remove everything inside, except for the __init__.py file.
It will remove all the migrations files inside your project. Run the python manage.py showmigrations again.
Create the initial migrations, run python manage.py makemigrations
In this case, you won’t be able to apply the initial migration because the database table already exists. What we want to do is to fake this migration instead. Run command
Run python manage.py showmigrations again
That’s all. You should have fresh migration files by now. I hope this helped. Check out more django-tutorials. If you want to structure a Django project, then you check out this article on structuring a Django app for beginners.