Cómo simplificar las migraciones en Django 1.7?


Ya hay preguntas similares para South, pero he comenzado mi proyecto con Django 1.7 y no estoy usando South.

Durante el desarrollo se han creado muchas migraciones, sin embargo, el software aún no está delievered y no existe ninguna base de datos que deba ser migrada. Por lo tanto, me gustaría reiniciar las migraciones como si mi modelo actual fuera el original y recrear todas las bases de datos.

¿Cuál es la forma recomendada de hacerlo?

EDITAR: A partir de Django 1.8 hay un nuevo comando llamado squashmigrations que más o menos resuelve el problema descrito aquí.

Author: OrangeDog, 2014-05-20

11 answers

En la versión Django 1.7 de las migraciones, la funcionalidad de reset que solía estar en el Sur se ha eliminado en favor de una nueva funcionalidad para 'aplastar' sus migraciones. Se supone que esta es una buena manera de mantener el número de migraciones bajo control.

Https://docs.djangoproject.com/en/dev/topics/migrations/#squashing-migrations

Si todavía desea comenzar de cero, supongo que todavía podría vaciar la tabla de migraciones y eliminar las migraciones después de lo cual se ejecutaría makemigrations de nuevo.

 36
Author: tijs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-05-20 09:17:00

Yo me encargo. Me acabo de dar cuenta de esto y es bueno.

  • Primero, para borrar la tabla de migraciones:

    ./manage.py migrate --fake <app-name> zero
    
  • Elimina la carpeta app-name/migrations/ o su contenido.

  • Hacer las migraciones:

    ./manage.py makemigrations <app-name>
    
  • Finalmente ordena tus migraciones sin hacer otros cambios en la base de datos:

    ./manage.py migrate --fake <app-name>
    
 133
Author: kzorro,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-08-19 04:18:03

Acabo de tener el mismo problema. Aquí está mi solución.

#!/bin/sh
echo "Starting ..."

echo ">> Deleting old migrations"
find . -path "*/migrations/*.py" -not -name "__init__.py" -delete
find . -path "*/migrations/*.pyc"  -delete


# Optional
echo ">> Deleting database"
find . -name "db.sqlite3" -delete

echo ">> Running manage.py makemigrations"
python manage.py makemigrations

echo ">> Running manage.py migrate"
python manage.py migrate

echo ">> Done"

El comando find: http://unixhelp.ed.ac.uk/CGI/man-cgi?find

 21
Author: Abdelhamid Ba,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-07-21 18:56:12

Asumiendo que esta es la estructura de su proyecto,

project_root/
    app1/
        migrations/
    app2/
        migrations/
    ...
    manage.py
    remove_migrations.py

Puede ejecutar el script remove_migrations.py desde el lugar indicado anteriormente para eliminar todos los archivos de migraciones.

#remove_migrations.py
"""
Run this file from a Django =1.7 project root. 
Removes all migration files from all apps in a project.
""" 
from unipath import Path

this_file = Path(__file__).absolute()
current_dir = this_file.parent
dir_list = current_dir.listdir()

for paths in dir_list:
    migration_folder = paths.child('migrations')
    if migration_folder.exists():
        list_files = migration_folder.listdir()
        for files in list_files:
            split = files.components()
            if split[-1] != Path('__init__.py'):
                files.remove()

Eliminar manualmente puede ser agotador si tiene un proyecto elaborado. Esto me ahorró mucho tiempo. Eliminar archivos de migración es seguro. Lo he hecho una enésima vez sin tener que hacer frente a ningún problema...aun.

Sin embargo, cuando eliminé la carpeta migraciones, makemigrations o migrate no creó el carpeta para mí. El script se asegura de que la carpeta de migración con su __init__.py permanezca en su lugar, solo borrando los archivos de migración.

 7
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-25 09:10:50
  1. Eliminar archivos: delete_migrations.py (en la raíz de prj):
import os

for root, dirs, files in os.walk(".", topdown=False):
  for name in files:
      if '/migrations' in root and name != '__init__.py':
          os.remove(os.path.join(root, name))
  1. DELETE FROM django_migrations Where app in ('app1', 'app2');

  2. ./manage.py makemigrations

  3. ./manage.py migrate fake fake

O, puede escribir la migración de todo esto

 6
Author: Ibrohim Ermatov,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-01 09:20:31

Pruebo diferentes comandos y algunas de las respuestas me ayudan. Solo esta secuencia en mi caso arregló ambas dependencias rotas en las migraciones en MYAPP y limpió todas las migraciones pasadas comenzando desde cero.

Antes de hacer esto, asegúrese de que la base de datos ya está sincronizada (por ejemplo, no agregue un nuevo campo de modelo aquí o cambie las opciones de Meta).

rm -Rf MYAPP/migrations/*
python manage.py makemigrations --empty MYAPP
python manage.py makemigrations
python manage.py migrate --fake MYAPP 0002

Donde 0002 es el número de migración devuelto por el último comando makemigrations.

Ahora puede ejecutar makemigrations / migrate de nuevo normalmente porque la migración 0002 se almacena pero no se refleja en la base de datos ya sincronizada.

 4
Author: chirale,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-12-06 09:29:22

Si no le importan las migraciones anteriores, ¿qué tal eliminar todas las migraciones en el directorio migrations/? comenzará la secuencia de migración desde cero, tomando su modelo actual como referencia como si hubiera escrito todo el modelo ahora.

Si no confías en mí lo suficiente para eliminarlos, entonces trata de alejarlos.

 3
Author: vokimon,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-09-04 19:55:49

Una forma sencilla es

Vaya a cada aplicación y elimine los archivos de migración.

Luego vaya a la tabla django-migrtaions en la base de datos y truncarla(eliminar todas las entradas).

Después de eso, puede crear migraciones una vez más.

 1
Author: sprksh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-06 11:36:15

Cd al directorio src cd /path/to/src

Eliminar directorios de migración rm -rf your_app/migrations/

Tenga en cuenta que esto debe hacerse para cada aplicación por separado

Migrar python3.3 manage.py migrate

Si desea comenzar de nuevo python3.3 manage.py makemigrations your_app

 0
Author: Rubber Duck,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-03-03 21:10:44

Si estás en modo desarrollo y solo quieres reiniciar todo (base de datos, migraciones, etc.), utilizo este script basado en la respuesta de Abdelhamid Ba. Esto borrará las tablas de la base de datos (Postgres), eliminará todos los archivos de migración, volverá a ejecutar las migraciones y cargará mis accesorios iniciales:

#!/usr/bin/env bash
echo "This will wipe out the database, delete migration files, make and apply migrations and load the intial fixtures."

while true; do
    read -p "Do you wish to continue?" yn
    case $yn in
        [Yy]* ) make install; break;;
        [Nn]* ) exit;;
        * ) echo "Please answer yes or no.";;
    esac
done

echo ">> Deleting old migrations"
find ../../src -path "*/migrations/*.py" -not -name "__init__.py" -delete

# Optional
echo ">> Deleting database"
psql -U db_user -d db_name -a -f ./reset-db.sql

echo ">> Running manage.py makemigrations and migrate"
./migrations.sh

echo ">> Loading initial fixtures"
./load_initial_fixtures.sh

echo ">> Done"

Reset-db.archivo sql:

DO $$ DECLARE
    r RECORD;
BEGIN
    -- if the schema you operate on is not "current", you will want to
    -- replace current_schema() in query with 'schematodeletetablesfrom'
    -- *and* update the generate 'DROP...' accordingly.
    FOR r IN (SELECT tablename FROM pg_tables WHERE schemaname = current_schema()) LOOP
        EXECUTE 'DROP TABLE IF EXISTS ' || quote_ident(r.tablename) || ' CASCADE';
    END LOOP;
END $$;

Migration.sh archivo:

#!/usr/bin/env bash
cd ../../src
./manage.py makemigrations
./manage.py migrate

Load_initial_fixtures.sh archivo:

#!/usr/bin/env bash
cd ../../src
./manage.py loaddata ~/path-to-fixture/fixture.json

Solo asegúrese de cambiar las rutas a corresponde a su aplicación. Me personalmente tienen estos scripts en una carpeta llamada project_root / script / local, y las fuentes de django están en project_root / src.

 0
Author: mrmuggles,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-06-24 07:01:35

Después de eliminar cada carpeta de "migraciones" en mi aplicación (manualmente), corrí:

./manage.py dbshell
delete from django_migrations;

Entonces pensé que podía hacer ./manage.py makemigrations para regenerarlos a todos. Sin embargo, no se detectaron cambios. Luego intenté especificar una aplicación a la vez: ./manage.py makemigrations foo, ./manage.py makemigrations bar. Sin embargo, esto dio lugar a dependencias circulares que no se pudieron resolver.

Finalmente, ejecuté un solo comando makemigrations que especificaba TODAS mis aplicaciones (sin ningún orden en particular):

./manage.py makemigrations foo bar bike orange banana etc

Esta vez, funcionó-circular las dependencias se resolvían automáticamente (se creaban archivos de migración adicionales cuando era necesario).

Entonces fui capaz de ejecutar ./manage.py migrate --fake y estaba de vuelta en el negocio.

 0
Author: shacker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-11-04 18:23:16