Как удалить все миграции django
Перейти к содержимому

Как удалить все миграции django

  • автор:

Deleting Migrations In Django Project

Steve Matindi

Sometimes deleting migrations can be doubting, but with this reference you can now easily delete and make migrations for your Django project with ease. Most of the times when one is in need of deleting migrations, is due to situations like e.g when one gets table errors not existing or when their is too much duplicates.

Below are the steps to rectify issues with Django migrations:

Step1: We need to delete existing migrations by running this script within our project’s folder :

Step 2: If you’re using MySQL as your database, login and delete migrations using the following commands:

Step 3: With the migrations gone, lets do this to do migrations now:

Finally run your server using the following command:

If everything goes well, any error experienced or seen while on debug mode should disappear.

Сбросить миграции в Django

Сбросить миграции в Django

При работе с базами данных нам часто приходится перезагружать базу данных, потому что мы заполняем ее бесполезными данными. Иногда мы даже создаем базу данных на основе схемы базы данных, подверженной ошибкам. Иногда мы даже меняем бизнес-логику, которая корректирует весь дизайн базы данных. Эти ситуации довольно распространены в области компьютерных наук, и для их обработки созданы несколько хороших инструментов и команд.

В Django, если мы попадаем в такую ​​ситуацию, мы должны сбросить миграции и базу данных. При сбросе миграций у нас есть несколько вариантов в списке.

  1. Сбросить всю базу данных
  2. Вернуть приложение Django к некоторым старым миграциям.

Сбросить всю базу данных в Django

  1. Если мы используем базу данных SQLite по умолчанию в Django, мы можем удалить файл базы данных db.sqlite3 , а затем удалить все папки migrations во всех приложениях. После удаления папок migrations мы можем переделать миграции и перенести их с помощью двух команд; а именно python manage.py makemigrations и python manage.py migrate .
  2. Если мы используем какую-либо другую реляционную базу данных, такую ​​как PostgreSQL или MySQL, мы можем либо удалить все таблицы с помощью инструмента управления базой данных, такого как pgAdmin , DBeaver и т. Д., Либо вручную, используя командную строку. Или мы можем создать совершенно новую базу данных, а затем подключить ее к нашему проекту Django. Обратите внимание, что в обоих случаях нужно сначала удалить все папки migrations , а затем заново выполнить миграции и, наконец, перенести их.
  3. Другой вариант — использовать команду Django manage.py , чтобы очистить для нас всю базу данных. Команда — python manage.py flush . Опять же, после использования этой команды мы должны удалить все папки migrations , а затем выполнить новые миграции.

Вернуть приложение Django к его старым миграциям

Если нам не нужно сбрасывать всю базу данных, а откатывать миграции для определенного приложения Django, у нас есть два варианта для этого. Во-первых, мы можем отменить текущие миграции приложения Django на некоторые старые миграции. Во-вторых, мы можем сбросить все миграции для приложения Django.

Если нам нужно вернуться с какой-то последней миграции, скажем, 0014, на более старую миграцию, скажем, 0008, мы можем использовать следующие команды.

И, если нам нужно сбросить все миграции для приложения Django, мы можем использовать следующую команду.

Django: Safely Remove Old Migrations?

I’ve got a Django app with a lot of out-of-date migrations. I’d like to remove the old migrations and start fresh.

The app has 14 different «migrations» folders.

Here is what a few of them look like:

enter image description here

enter image description here

enter image description here

Is it safe to remove all the contents from each of these folders? Or, do I have to make sure to only remove some of the files — and if so which files?

https://amdy.su/wp-admin/options-general.php?page=ad-inserter.php#tab-8

6 Answers 6

You should never just delete migrations before unapplying them, or it will be a nightmare when you want to apply new migrations.

To unapply migrations you should do the following:

Use the python manage.py migrate your_app_name XXXX in case you want to unapply migrations after the XXXX migration. Otherwise use python manage.py migrate your_app_name zero to completely unapply all migrations.

Remove the .pyc files under /migrations/_pycache_/ that you have unapplied.

Remove the .py files under migrations/ that you have unapplied.

Now you can create new migrations without any headaches.

If what you’re looking for is to squash all the migrations into one, do the steps above removing all migrations and then run python manage.py makemigrations your_app_name to create a single migration file. After that just run python manage.py migrate your_app_name and you’re done.

Jordan Mora's user avatar

That depends. If you have a production database (or any database you cannot simply drop and recreate), then the answer is no, you cannot safely remove migrations.

If you do not have any permanent databases, then yes, you can remove all migrations, run python manage.py makemigrations —initial and it will create fresh migrations based on your current models.

Also, you should check if any of the migrations are custom data migrations written by hand. If there are any, you might want to keep those.

The .pyc files are generally safe to remove, provided the related .py files are still there.

your first screenshot is not Django and looks like a JS project of some sort.

  1. The json and js files are unrelated to the django migrations as well as __pycache__ folder. You can delete all off them.
  2. If you mean «previously applied and no longer needed as the project only needs the latest version of the migrations» you don’t want to remove but squash them instead with squashmigrations which reduces the files you have to two, init file and the initial migration file, this way your project still works.
  3. If by remove you mean you no longer need them because you already changed the models so much that the previous migrations aren’t even used other than being applied and unapplied without ever being used, doesn’t matter, go to step 2 and do that instead of deleting the files manually. When you create migrations on your applications one by one, you also create migration dependency tree, well, django does. And it is really hard to keep track of after some point, if you try to delete everything thinking you can create new migration files with ease, trust me as someone who experienced otherwise, it does not work like that. It is way simpler to let django handle the migration squashing, it optimizes the migration meaning that it also deletes the unused ones in your final state.

Işık Kaplan's user avatar

Having marked one of the answers provided previously as being accepted, here is a summary of a few things I learned:

  • Deleting Django migrations is generally a bad idea.
  • Django keeps track of what’s in your db through these migration files, as well as through a table it creates in your db, and if you delete any of this Django will start throwing errors on migrate that can be hard to fix.

I was getting some of those hard-to-fix errors. Here is what I did to fix it:

  • Ran migrate on the production server.
  • When I got an error, it would tell me how the db was out of sync with what Django expected. I corrected that manually by directly editing the db with an sql client.
  • E.g. If it said a key existed that wasn’t supposed to exist, I deleted the relevant index from the indicated table.
  • Or if it said a table existed that wasn’t supposed to exist, I backed up the table to a file, and deleted the table. Migrate then created the table, and then I repopulated it with data from the backup.
  • In the case of many-to-many tables, once Django had re-created them, I deleted all the new Django-created tables, and restored them from a backup created on my local dev system, which had already had all the latest migrations run on it.

Eventually I was able to complete all migrations successfully.

I have a feeling I lucked out and the above won’t work in all cases! I’ve learned a lot about Django and migrations and will be much more careful about this in the future.

Reset Migrations in Django

There’re 2 scenarios you will face in real project. This article will show you them.

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

Note that, you should not delete __init__.py file.

Run following commands to remove all migrations files inside your project.

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:

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.

Run following commands to remove all migrations files 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:

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *