django.db.migrations.exceptions.InconsistentMigrationHistory - python

When I run python manage.py migrate on my Django project, I get the following error:
Traceback (most recent call last):
File "manage.py", line 22, in <module>
execute_from_command_line(sys.argv)
File "/home/hari/project/env/local/lib/python2.7/site- packages/django/core/management/__init__.py", line 363, in execute_from_command_line
utility.execute()
File "/home/hari/project/env/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 355, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/home/hari/project/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 283, in run_from_argv
self.execute(*args, **cmd_options)
File "/home/hari/project/env/local/lib/python2.7/site-packages/django/core/management/base.py", line 330, in execute
output = self.handle(*args, **options)
File "/home/hari/project/env/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 86, in handle
executor.loader.check_consistent_history(connection)
File "/home/hari/project/env/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 298, in check_consistent_history
connection.alias,
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency account.0001_initial on database 'default'.
I have a user model like below:
class User(AbstractUser):
place = models.CharField(max_length=64, null=True, blank=True)
address = models.CharField(max_length=128, null=True, blank=True)
How can I solve this problem?

Since you are using a custom User model, you can do 4 steps:
Comment out django.contrib.admin in your INSTALLED_APPS settings
INSTALLED_APPS = [
...
#'django.contrib.admin',
...
]
Comment out admin path in urls.py
urlpatterns = [
...
#path('admin/', admin.site.urls)
...
]
Then run
python manage.py migrate
When done, uncomment all back

Lets start off by addressing the issue with most of the answers on this page:
You never have to drop your database if you are using Django's migration system correctly and you should never delete migrations once they are comitted
Now the best solution for you depends on a number of factors which include how experienced you are with Django, what level of understanding you have of the migration system, and how valuable the data in your database is.
In short there are two ways you can address any migration error.
Take the nuclear option. Warning: this is only an option if you are working alone. If other people depend on existing migrations you cannot just delete them.
Delete all of your migrations, and rebuild a fresh set with python3 -m manage makemigrations. This should remove any problems you had with dependencies or inconsistencies in your migrations.
Drop your entire database. This will remove any problems you had with inconsistencies you had between your actual database schema and the schema you should have based on your migration history, and will remove any problems you had with inconsistencies between your migration history and your previous migration files [this is what the InconsistentMigrationHistory is complaining about].
Recreate your database schema with python3 -m manage migrate
Determine the cause of the error and resolve it, because (speaking from experience) the cause is almost certainly something silly you did. (Generally as a result of not understanding how to use the migration system correctly). Based on the error's I've caused there are three categories.
Inconsistencies with migration files. This is a pretty common one when multiple people are working on a project. Hopefully your changes do not conflict and makemigrations --merge can solve this one, otherwise someone is going to have to roll back their migrations to the branching point in order to resolve this.
Inconsistencies between your schema and your migration history. To manage this someone will have either edited the database schema manually, or deleted migrations. If they deleted a migration, then revert their changes and yell at them; you should never delete migrations if others depend on them. If they edited the database schema manually, revert their changes and then yell at them; Django is managing the database schema, no one else.
Inconsistencies between your migration history and your migrations files. [This is the InconsistentMigrationHistory issue the asker suffers from, and the one I suffered from when I arrived at this page]. To manage this someone has either manually messed with the django_migrations table or deleted a migration after it was applied. To resolve this you are going to have to work out how the inconsistency came about and manually resolve it. If your database schema is correct, and it is just your migration history that is wrong you can manually edit the django_migrations table to resolve this. If your database schema is wrong then you will also have to manually edit that to bring it in line with what it should be.
Based on your description of the problem and the answer you selected I'm going to assume you are working alone, are new to Django, and don't care about your data. So the nuclear option may be right for you.
If you are not in this situation and the above text looks like gibberish, then I suggest asking the Django User's Mailing List for help. There are very helpful people there who can help walk you through resolving the specific mess you are in.
Have faith, you can resolve this error without going nuclear!

Your django_migrations table in your database is the cause of inconsistency and deleting all the migrations just from local path won't work.
You have to truncate the django_migrations table from your database and then try applying the migrations again. It should work but if it does not then run makemigrations again and then migrate.
Note: don't forget to take a backup of your data.

This happened to me in a new project after I added a custom User model, per the recommendation in the django docs.
If you’re starting a new project, it’s highly recommended to set up a custom user model, even if the default User model is sufficient for you.
Here is what I did to solve the problem.
Delete the database db.sqlite3.
Delete the app/migrations folder.
Per #jackson, temporarily comment out django.contrib.admin.
INSTALLED_APPS = [
...
#‘django.contrib.admin’,
...
]
Also comment out the admin site in urls.py:
urlpatterns = [
path('profile/', include('restapp.urls')),
#path('admin/', admin.site.urls),
]
If you don't comment out the path('admin/'), you will get error "LookupError: No installed app with label 'admin'" when you run
python manage.py migrate
After the migrations finish, uncomment both of the above.

Here how to solve this properly.
Follow these steps in your migrations folder inside the project:
Delete the _pycache_ and the 0001_initial files.
Delete the db.sqlite3 from the root directory (be careful all your data will go away).
on the terminal run: python manage.py makemigrations
python manage.py migrate
Voila.

Problem
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency account.0001_initial on database 'default'.
So we can migrate database without admin(admin.0001_initial) firstly.
After its dependency migrated, execute commands to migrate admin.0001_initial.
Solution
remove 'django.contrib.admin' from INSTALLED_APPS in settings.py.
execute commands:
Python manage.py makemigrations appname
Python manage.py migrate appname
add 'django.contrib.admin' to INSTALLED_APPS in settings.py file.
execute commands again:
Python manage.py makemigrations appname
Python manage.py migrate appname

Before performing any other steps, back up your database. Then back it up again.
Remove any custom user model code out of the way, disable your custom model and app in settings, then:
python manage.py dumpdata auth --natural-primary --natural-foreign > auth.json
python manage.py migrate auth zero # This will also revert out the admin migrations
Then add in your custom model, set it in settings, and re-enable the app. Make sure you have no migrations on this app yet.
Then:
python manage.py makemigrations <your-app>
python manage.py migrate
python manage.py loaddata auth.json # Assumes your user-model isn't TOO dissimilar to the standard one.
Done!

Solved by commenting app admin before migration in settings.py
django.contrib.admin
and in urls.py,
('admin/', admin.site.urls)
uncomment after migrate

Just delete all the migrations folders, __pycache__, .pyc files:
find . | grep -E "(__pycache__|\.pyc|\.pyo$|migrations)" | xargs rm -rf
then, run:
python manage.py makemigrations
python manage.py migrate

When you are doing some changes to default user model or you are making a custom user model by abstractuser then lot of times you will face that error
1: Remember when we create a superuser then for logging in we need username and password but if you converted USERNAME_FIELD = 'email' then now you can't login with username and password because your username field is converted into email....
and if you try to make another superuser then it will not ask for username it will only ask for email and password and then after creating superuser by email and password only when you try to login in admin pannel then it will throw that error because there is not any username and username field is required
2: That's why after creating custom user model during migrate it will throw error so for
resolving it first add AUTH_USER_MODEL = 'appname.custommodelname' (appname is the app name where you definded your custom user model and custom model name is the name of the model which you gave to your custom user model) in your settings.py
3: Then delete the migrations folder of that app where you created that custom user model then delete the database db.sqlite3 of the project
4: Now run migrations python manage.py makemigrations appname(that app name where you defined your custom user model)
5: Then Migrate it by python manage.py migrate
6: That's it Now it is Done

In my case the problem was with pytest starting, where I just altered --reuse-db to --create-db, run pytest, and changed it back. This fixed my problem

You can delete directly db.sqlite3, then migrate a new database is automatically generated. It should fix it.
rm sqlite3.db
python manage.py makemigrations
python manage.py migrate

just delete the sqlite file or run flush the databse 'python manage.py flush'
and then run makemigrations and migrate commands respectively.

when you create a new Django project and run
python manage.py migrate
The Django will create 10 tables for you by default including one auth_user table and two start with auth_user.
when you want to create a custom user model inherit from AbstractUser, you will encounter this problem with error message as follow:
django.db.migrations.exceptions.InconsistentMigrationHistory: Migration admin.0001_initial is applied before its dependency account.0001_initial on database 'default'.
I solve this problem by dropping my entire database, and create a new one. And this replaced the three tables I mentioned.

Your Error is essentially:
Migration "B" is applied before its dependency "A" on database 'default'.
Sanity Check: First, open your database and look at the records in the 'django_migrations' table. Records should be listed in Chronological order (ex: A,B,C,D...).
Make sure that the name of the "A" Migration listed in the error matches the name of the "A" migration listed in the database. (They can differ if you had previously, manually, edited or deleted or renamed migration files)
To Fix This, rename migration A. either in the database or rename the filename. BUT make sure the changes matches up with what other developers on your team have in their databases (or the changes matches what on your production database)

The order of INSTALLED_APPS seems important.
If you always put your recent works on top/beginning of the list they'll always be loaded properly in regard to django.contrib.admin. Moving my works to the beginning of the INSTALLED_APPS list fixed this problem for me.
The reason Kun Shi's solution may have worked maybe it ran the migrations in a different order.

There is another reason besides user error that can lead to this sort of problem: a known issue with Django when it comes to squashed migrations.
We have a series of migrations that work perfectly fine in Python 2.7 + Django 1.11. Running makemigrations or migrate always works as it should, etc., even (for the purpose of testing) when the database is freshly re-created.
However, as we move a project to Python 3.6 (currently using the same Django 1.11) I've been stuck trying to figure out why the same migrations apply just fine only the first time they are run. After that, any attempt to run makemigrations or even just migrate results in the error:
django.db.migrations.exceptions.InconsistentMigrationHistory
wherein migration foo.0040-thing is applied before its dependency foo.0038-something-squashed-0039-somethingelse (we only happen to have that one squashed migration... the rest are much more straightforward).
What's bugged me for a while is why this only happens on Python 3. If the DB is truly inconsistent this should be happening all the time. That the migrations appear to work perfectly fine the first time they are applied was equally confounding.
After much searching (including the present Q&A thread), I stumbled upon the aforementioned Django bug report. Our squash migration did indeed use the b prefix in the replaces line (e.g., replaces = [(b'', 'foo.0038-defunct'),.......]
Once I removed the b prefixes from the replaces line it all worked normally.

If you are working on an empty database a quick fix could be running the migrations for the account app, before any other app migrations.
$ ./manage.py migrate account
And then:
$ ./manage.py migrate

How to fix (Without delete migration folder or entire database)
Backup your database
Comment out your app in INSTALLED_APPS and AUTH_USER_MODEL = 'account.User' in your settings.py
python manage.py admin zero
Undo step 2
python manage.py migrate
Why this problem occured?
django admin app depends on AUTH_USER_MODEL which is default auth model when you create your django project.
If you migrate project models before change the AUTH_USER_MODEL, django admin app apply migration as django auth model dependency. However, you change that dependency and want to migrate models again. So, the problem is occured here; admin models applied before its dependency, which is your User model now, applied. Thus, You should revert admin models migrations and then try it again.

First delete all the migrations and db.sqlite3 files and follow these steps:
$ ./manage.py makemigrations myapp
$ ./manage.py squashmigrations myapp 0001(may be differ)
Delete the old migration file and finally.
$ ./manage.py migrate

If that exception was reveal itself while you are trying to create your own User model instead of standard follow that instruction
I have found my problem resolve by follow that instruction step by step:
Create a custom user model identical to auth.User, call it User (so
many-to-many tables keep the same name) and set db_table='auth_user'
(so it uses the same table)
Throw away all your migrations
Recreate a fresh set of migrations
Sacrifice a chicken, perhaps two if you're anxious; also make a backup of your database
Truncate the django_migrations table
Fake-apply the new set of migrations
Unset db_table, make other changes to the custom model, generate migrations, apply them
It is highly recommended to do this on a database that enforces
foreign key constraints. Don't try this on SQLite on your laptop and
expect it to work on Postgres on the servers!

If you set AUTH_USER_MODEL in settings.py like this:
AUTH_USER_MODEL = 'custom_user_app_name.User'
you should comment this line before run makemigration and migrate commands. Then you can uncomment this line again.

when you create a new project and with no apps, you run the
python manage.py migrate
the Django will create 10 tables by default.
If you want create a customer user model which inherit from AbstractUser after that, you will encounter this problem as follow message:
django.db.migrations.exceptions.InconsistentMigrationHistory:
Migration admin.0001_initial is applied before its dependency
account.0001_initial on database 'default'.
finally,
I drop my entire databases and run

I encountered this when migrating from Wagtail 2.0 to 2.4, but have seen it a few other times when a third party app squashes a migration after your current version but before the version you’re migrating to.
The shockingly simple solution in this case at least is:
./manage.py migrate
./manage.py makemigrations
./manage.py migrate
i.e. run a single migrate before trying to makemigrations.

This Problem will come most of the time if you extend the User Model post initial migration. Because whenever you extend the Abstract user it will create basic fields which were present un the model like email, first_name, etc.
Even this is applicable to any abstract model in django.
So a very simple solution for this is either create a new database then apply migrations or delete [You all data will be deleted in this case.] the same database and reapply migrations.

I have to drop my database to and then run makemigrations and migrate again for this to be resolved on my part.

delete migrations folder and db.sqlite3 and type in the cmd
python manage.py makemigrations

django.db.migrations.exceptions.InconsistentMigrationHistory #On Creating Custom User Model
I had that same issue today, and none of the above solutions worked, then I thought to erase all the data from my local PostgreSQL database using this following command
-- Drop everything from the PostgreSQL database.
DO $$
DECLARE
q TEXT;
r RECORD;
BEGIN
-- triggers
FOR r IN (SELECT pns.nspname, pc.relname, pt.tgname
FROM pg_catalog.pg_trigger pt, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace AND pc.oid=pt.tgrelid
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pt.tgisinternal=false
) LOOP
EXECUTE format('DROP TRIGGER %I ON %I.%I;',
r.tgname, r.nspname, r.relname);
END LOOP;
-- constraints #1: foreign key
FOR r IN (SELECT pns.nspname, pc.relname, pcon.conname
FROM pg_catalog.pg_constraint pcon, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace AND pc.oid=pcon.conrelid
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pcon.contype='f'
) LOOP
EXECUTE format('ALTER TABLE ONLY %I.%I DROP CONSTRAINT %I;',
r.nspname, r.relname, r.conname);
END LOOP;
-- constraints #2: the rest
FOR r IN (SELECT pns.nspname, pc.relname, pcon.conname
FROM pg_catalog.pg_constraint pcon, pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace AND pc.oid=pcon.conrelid
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pcon.contype<>'f'
) LOOP
EXECUTE format('ALTER TABLE ONLY %I.%I DROP CONSTRAINT %I;',
r.nspname, r.relname, r.conname);
END LOOP;
-- indicēs
FOR r IN (SELECT pns.nspname, pc.relname
FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pc.relkind='i'
) LOOP
EXECUTE format('DROP INDEX %I.%I;',
r.nspname, r.relname);
END LOOP;
-- normal and materialised views
FOR r IN (SELECT pns.nspname, pc.relname
FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pc.relkind IN ('v', 'm')
) LOOP
EXECUTE format('DROP VIEW %I.%I;',
r.nspname, r.relname);
END LOOP;
-- tables
FOR r IN (SELECT pns.nspname, pc.relname
FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pc.relkind='r'
) LOOP
EXECUTE format('DROP TABLE %I.%I;',
r.nspname, r.relname);
END LOOP;
-- sequences
FOR r IN (SELECT pns.nspname, pc.relname
FROM pg_catalog.pg_class pc, pg_catalog.pg_namespace pns
WHERE pns.oid=pc.relnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pc.relkind='S'
) LOOP
EXECUTE format('DROP SEQUENCE %I.%I;',
r.nspname, r.relname);
END LOOP;
-- extensions (only if necessary; keep them normally)
FOR r IN (SELECT pns.nspname, pe.extname
FROM pg_catalog.pg_extension pe, pg_catalog.pg_namespace pns
WHERE pns.oid=pe.extnamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
) LOOP
EXECUTE format('DROP EXTENSION %I;', r.extname);
END LOOP;
-- aggregate functions first (because they depend on other functions)
FOR r IN (SELECT pns.nspname, pp.proname, pp.oid
FROM pg_catalog.pg_proc pp, pg_catalog.pg_namespace pns, pg_catalog.pg_aggregate pagg
WHERE pns.oid=pp.pronamespace
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast')
AND pagg.aggfnoid=pp.oid
) LOOP
EXECUTE format('DROP AGGREGATE %I.%I(%s);',
r.nspname, r.proname,
pg_get_function_identity_arguments(r.oid));
END LOOP;
-- routines (functions, aggregate functions, procedures, window functions)
IF EXISTS (SELECT * FROM pg_catalog.pg_attribute
WHERE attrelid='pg_catalog.pg_proc'::regclass
AND attname='prokind' -- PostgreSQL 11+
) THEN
q := 'CASE pp.prokind
WHEN ''p'' THEN ''PROCEDURE''
WHEN ''a'' THEN ''AGGREGATE''
ELSE ''FUNCTION''
END';
ELSIF EXISTS (SELECT * FROM pg_catalog.pg_attribute
WHERE attrelid='pg_catalog.pg_proc'::regclass
AND attname='proisagg' -- PostgreSQL ≤10
) THEN
q := 'CASE pp.proisagg
WHEN true THEN ''AGGREGATE''
ELSE ''FUNCTION''
END';
ELSE
q := '''FUNCTION''';
END IF;
FOR r IN EXECUTE 'SELECT pns.nspname, pp.proname, pp.oid, ' || q || ' AS pt
FROM pg_catalog.pg_proc pp, pg_catalog.pg_namespace pns
WHERE pns.oid=pp.pronamespace
AND pns.nspname NOT IN (''information_schema'', ''pg_catalog'', ''pg_toast'')
' LOOP
EXECUTE format('DROP %s %I.%I(%s);', r.pt,
r.nspname, r.proname,
pg_get_function_identity_arguments(r.oid));
END LOOP;
-- nōn-default schemata we own; assume to be run by a not-superuser
FOR r IN (SELECT pns.nspname
FROM pg_catalog.pg_namespace pns, pg_catalog.pg_roles pr
WHERE pr.oid=pns.nspowner
AND pns.nspname NOT IN ('information_schema', 'pg_catalog', 'pg_toast', 'public')
AND pr.rolname=current_user
) LOOP
EXECUTE format('DROP SCHEMA %I;', r.nspname);
END LOOP;
-- voilà
RAISE NOTICE 'Database cleared!';
END; $$;
After this you can run django command for migrations
python manage.py makemigrations
python manage.py migrate
And Absolutely that will work . Thank You.

Comment django.contrib.admin from installed apps and also comment path('admin/', admin.site.urls),then rerun makemigrations and then migrate. It will solve your issue. For more info go here

These steps can as well work
Drop your entire database
Make a new migration
These few steps can solve it for you, and I think its best when you have multiple contributors to the sam project.

Related

strange migration from django to postgres DB. How to save an exist data

I have walking on a strange way, but it is result of circumstances.
I had to been generate single models.py from exist postgres DB by inspect_db.
Next I fix some field (was a few problem with keys), and create 2 apps inside this project. So now I have 3 models.py (them are split models.py, whitch was generate by inspect_db). managed = True was added. Classes have same links and datatypes like in the database
Next I wish to integrate this models to exist database. I make migration, I migrate and in the end DB have only system django tables (auth_, django_migrations etc.) None from my classes (although migrate files were create). So I tryied to delete migrations catalogs and repeat makemigrations and migrate, but terminal threw it:
Operations to perform:
Apply all migrations: admin, auth, contenttypes, sessions
Running migrations:
No migrations to apply.
(forest-venv) user#user-HP-Z800-Workstation ~/MyProjects/forest-venv/lesoved $ python manage.py runserver 8001
Performing system checks...
If I try make migrates again - no changes. I tryied to delete info about my apps in django_migrations table - no result.
So my questions:
- It is possible to integrate new models into exist database (if names, keyes and formats is ok)?
- Integration is possible by the way where data from exist database is saved after migrations?
- How to return possobillity of make migrations? now it isn't work.
The trick when using an existing database is to make sure you start from a well-defined state: First get Django to the exact same state as your db, and only after that start making changes to your models. So these are the steps:
Check that your database doesn't have a django-migrations table, delete it using SQL if needed. (Note: I'm assuming this db isn't generated by Django to start with and you're creating a fresh django application)
Create your models with inspectdb. If needed, rename the models to have proper CamelCase. If you rename models or fields that would change the table or column name in the db, make sure to set db_table (Meta options of your model) and db_column (as field attribute).
Run manage.py makemigrations. Check the migration files for your models, just to be sure the names match with your db.
For your own apps, run manage.py migrate <app> --fake. This will add the migrations to django-migrations table in your db as if they ran, without actually running them.
Then run manage.py migrate to create the django provided tables (auth, contenttype, session etc...)
Now you are at the state where you can start changing things. If you change the model and run makemigrations it should create a migration just for your changes.

How to create a new table using model

So I have this django installation in which there are a bunch of migration scripts. They look like so:
00001_initial.py
00002_blah_blah.py
00003_bleh_bleh.py
Now I know these are "database building" scripts which will take stuff defined in models.py and run them against the db to "create" tables and stuff.
I want to create a new table(so I created its definition in models.py). For this, I have copied another model class and edited its name and fields and it is all fine. Lets call this new model class 'boom'.
My question is now how do I "create" this boom table using the migration script and the boom model?
I am worried that I might accidentally disrupt anything that is already in DB. How do I run the migration to create only boom table? How do I create a migration script specifically for it?
I know that it has something to do with manage.py and running migrate or runmigration (or is it sqlmigrate?...im confused). While creating the boom table, I dont want the database to go boom if you know what I mean :)
First, create a backup of your database. Copy it to your development machine. Try things out on that. That way it doesn't matter if it does go "boom" for some reason.
The first thing to do is
python manage.py showmigrations
This shows all the existing migrations, and it should show that they have been applied with an [X].
Then,
python manage.py makemigrations
Makes a new migration file for your new model (name 00004_...).
Then do
python manage.py migrate
to apply it. To undo it, go back to the state of migrations 00003, with
python manage.py migrate <yourappname> 00003
There are two steps to migrations in Django.
./manage.py makemigrations
will create the migration files that you see - these describe the changes that should be made to the database.
You also need to run
./manage.py migrate
this will apply the migrations and actually run the alter table commands in SQL to change the actual database structure.
Generally adding fields or tables won't affect anything else in the database. Be more careful when altering or deleting existing fields as that can affect your data.
The reason for two steps is so that you can make changes on a dev machine and once happy commit the migration files and release to your production environment. Then you run the migrate command on your production machine to bring the production database to the same state as your dev machine (no need for makemigrations on production assuming that your databases started the same).
My question is now how do I "create" this boom table using the
migration script and the boom model?
./manage.py makemigrations
I am worried that I might accidentally disrupt anything that is
already in DB.
The whole point of migrations, is that it doesn't
I know that it has something to do with manage.py and running migrate
or runmigration
For more information please refer to : https://docs.djangoproject.com/en/1.10/topics/migrations/
And rest assured that your database will not go boom! :-)
I solved it simply, changing the name of the new model to the original name, and then I checked if there is the table in the database, if not, I just create a new table with the old name with just a field like id.
And then clear migrations and create new migrations, migrate and verify table was fixed in DB and has all missing fields.
If it still doesn't work, then change the model name back to a new one.
but when django asks you if you are renaming the model you should say NO to get the old one removed properly and create a new one.
This type of error usually occurs when you delete some table in dB manually, and then the migration history changes in the tables are lost.
But it is not necessary to erase the entire database and start from scratch.

Django 1.8 migrate is not creating tables

yekabathula-macbookair2:roster yekabathula$ python manage.py migrate
Operations to perform:
Synchronize unmigrated apps: staticfiles, messages
Apply all migrations: admin, contenttypes, api, auth, sessions
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
Rendering model states... DONE
Applying contenttypes.0001_initial... OK
Applying auth.0001_initial... OK
Applying admin.0001_initial... OK
Applying api.0001_initial... OK
Applying contenttypes.0002_remove_content_type_name... OK
Applying auth.0002_alter_permission_name_max_length... OK
Applying auth.0003_alter_user_email_max_length... OK
Applying auth.0004_alter_user_username_opts... OK
Applying auth.0005_alter_user_last_login_null... OK
Applying auth.0006_require_contenttypes_0002... OK
Applying sessions.0001_initial... OK
yekabathula-macbookair2:roster yekabathula$ python manage.py syncdb
/Library/Python/2.7/site-packages/django/core/management/commands/syncdb.py:24: RemovedInDjango19Warning: The syncdb command will be removed in Django 1.9
warnings.warn("The syncdb command will be removed in Django 1.9", RemovedInDjango19Warning)
Operations to perform:
Synchronize unmigrated apps: staticfiles, messages
Apply all migrations: admin, contenttypes, api, auth, sessions
Synchronizing apps without migrations:
Creating tables...
Running deferred SQL...
Installing custom SQL...
Running migrations:
No migrations to apply.
After doing python manage.py migrate, tables are not created in database from my models.py it is able to create other tables from django_session etc. Is there anything else that I need to follow here ?
I was facing a similar problem in Django 1.10 and none of the above solutions worked for me.
What eventually worked was running this command:
python manage.py migrate --fake myappname zero
This reset all migrations (to the zeroth state)
This followed by :
python manage.py migrate myappname
created the tables for me.
If you do not want to roll back to the initial(zero) state but say to the migration number 0005(the last migration that worked), you can instead do this:
python manage.py migrate --fake myappname 0005
And then proceed with the actual migrate:
python manage.py migrate myappname
More details in the docs
In my case the __init__.py file was missing from the APP/migrations/ folder. If you don't have one, all it needs is an empty __init__.py file.
I ran into the same problem. After lots of digging, I found the solution.
I'm using django 1.11.
If you want to start-over,
1)delete all the files in your migrations folder except __init__.py
2)drop database
3)create database
4)python makemigrations
5)python migrate
if you have reset_db, instead of 2nd and 3rd steps you can use reset_db.
python manage.py reset_db
I am using MySQL and get into this issue after deleting 0001_initial.py migration file and all the custom tables evolved from DB to try to regenerate all they...
Solved this issue simply deleting these rows in django_migrations table...
After that, $ python manage.py migrate command regenerates all my custom tables again.
I had a similar problem and just figured it out.I have multiple databases. My local one (the one not being updated) is a MySQL database. The others are MS SQL Server and MySQL. I have routers to the other databases since I do not manage them and had (in Django 1.6) used the routers to indicate allow_sync() = False. With 1.7, I changed that to allow_migrate() = False. BUT I DID NOT ADD A ROUTER FOR MY LOCAL DATABASE. The default appears to be allow_migrate() = False if there is not one. As a result, the migrations just failed silently ( Reference: https://docs.djangoproject.com/en/1.7/topics/db/multi-db/). I added a router for my local DB, setting allow_migrate() to return True and now my migrations actually create my tables.
Change managed = True (if it is set to False) in models.py
class Meta:
managed = False
db_table = 'table_name'
To
class Meta:
managed = True
db_table = 'table_name'
I had a similar issue. I did everything stated above but nothing worked. Then I realized I had not added my model name in admin.py file in my app.
Along with everything stated above you have to also add your model name in admin.py file. You have to add it like this:
admin.site.register(model name)
This can be very frustrating, but here is method that worked for me.
First, if you've deleted the migration file go ahead and create it again
python manage.py makemigrations
Then compare the migration file with the SQL raw code and if it fit then apply migration
python manage.py sqlmigrate [app_name] 0001
python manage.py migrate
or you can simply pipe it from your command line or terminal
python manage.py sqlmigrate [app_name] 0001 | [psql] db_name username
BEGIN
CREATE TABLE
ALTER TABLE
COMMIT
NOTE: In my case I'm using postgresql. Though engine is similar to other database langauge, you might not get expected result.
Delete existing tables of the models in MySQL database.
Delete migration folder under app folder.
Delete all relative migration records in the table
"django_migrations" from MySQL.
Now you get clear model and database. Use
python manage.py makemigrations and python manage.py migrate
to create tables.
Hope to help you.
try this one,
run,
python manage.py makemigrations app_name
above command will make migrations, if successful then run second command or
check if you have typo in Installed_app and also check for AppConfig module
python manage.py migrate app_name
if above was successful, this will create the table in db
This solved the problem for me (I am using MySQL workbench by the way):
Run this sql: SET FOREIGN_KEY_CHECKS = 0;
Select all the tables in your django database (click on the first table, then press and hold shift, then click on the last table). Then right click and choose "Drop n tables" (where n is the number of tables you just selected)
then run python manage.py migrate
Finally restore foreign key check settings by running this sql: SET FOREIGN_KEY_CHECKS = 1;
Note: Before taking this drastic measure, I tried what Paulo Pessoa said in his comment, but still I got "No migrations to apply." messages. However, this solved the issue.
If you want to do it only for your application not from all the apps then Clear your application migrations records from 'django_migrations' table in your DB.
Python manage.py makemigrtions
python
Problem: : When you apply migrations in django for the first time, django creates table of that model in database and marks somewhere in its own file(class):
`initial = True`
When you then tries to alter the schema of that table it firstly checks
if initial = True
if an initial class attribute isn’t found, a migration will be considered “initial”
In case the initial = True we need to use 
python manage.py migrate --fake-initial
For an initial migration Django checks that all of those tables already exist in the database and fake-applies the migration if so. Similarly, for an initial migration that adds one or more fields Django checks that all of the respective columns already exist in the database and fake-applies the migration if so.
Fake initial migration uses both CreateModel() and AddField() methods.
Solution:
>> python manage.py makemigrations <AppName>
>> python manage.py migrate --fake-initial
To avoid deleting critical databases, you may also consider silencing properties below the Class Meta: for example this model:
class Blog(models.Model):
category = models.CharField(max_length=100)
title = models.CharField(max_length=100)
date_added = models.DateTimeField()
merits = models.CharField(max_length=300, blank=True)
demerits = models.CharField(max_length=300, blank=True)
class Meta:
managed = True
db_table = 'weblog'
verbose_name_plural = "Blog"
#property
def content_min(self):
return truncatechars(self.content, 50)
You can then run makemigrations and migrate and your table will be created.
Check if you have added your created app to you installed apps under settings.py.
The list should seem like this:
INSTALLED_APPS = [
'django.contrib.admin','django.contrib.auth','django.contrib.contenttypes',
'django.contrib.sessions', 'django.contrib.messages','django.contrib.staticfiles',
'YourCreatedApp',
]
in my case just one app's tables of project doesn't recreate!
and this line of code recreate them and successfully run!
python manage.py migrate --run-syncdb
however i couldn't find main reason caused this kind of problem!
Delete database
delete migration folder
run migrate command
run makemigrations command
run migrate command
It will create all tables perfectly
Change from sqlite3 to mysql in settings.py
Make sure you have correct information regarding database name and username-password
Delete existing migration
Make migration
And then migrate
Make sure each app's migrations folder has a __init__.py file.
I had a similar issue, the connection with DB was set correctly as all the django admin tables were created on DB side. However, no models appeared in models.py
What worked for me is running in the console:
python manage.py inspectdb > models.py
which wrote everything into a new models.py file which then I replaced with the one I had in the app folder. Then I could alter the
managed = False
into
managed = True
here the link to the documentation: https://docs.djangoproject.com/en/3.1/howto/legacy-databases/
If you are a begginer like me make sure your classes extend models.Model. Then makemigrations and migrate.
class Cook(models.Model):
email = models.Field()
I solved a similar problem by doing this:
Delete all migration files and pycache so what retains is init.py
Comment all implementations of that table in models, serializers, admin, urls and views
Do python manage.py makemigrations
Do python manage.py migrate
Then, uncomment all implementations of that table in models, serializers, admin, urls and views
Then, do python manage.py makemigrations
Then, do python manage.py migrate
To elaborate on #Leman-Kirme 's answer.
I had a similar problem where the table for the model I added into models.py of one of my apps wouldn't get created when making and applying migrations. I tried different solutions but nothing seemed to work and I really didn't want to flush my databases. So what I did was:
Delete all the files in the migrations folder except for _init_.py
Delete all records in databases' django_migrations tables.
Manually make a migration file (copied from another project and changed the content so that migration would only make a model that I was having troubles with). Please, note, that it seems like it should be initial migration, i.e. 0001_initial.py
Run it.
Voila, here comes the table!
If you want / need, instead of deleting previous migrations' files and records in the databases, you could backup them and restore afterwards. You gonna need to edit name of your manually-created migration from 0001_initial to something like <number_of_existing_migrations>_fix
That worked for me (but I ignored step 6), I hope someone finds this useful as well!
Gist: => Delete entry from django_migrations and run the migrate command again.
This answer takes help from other answers, but still writing as there are different cases and my answer might help in your case.
After creating migration, I think by mistake I ran the command python manage.py migrate campaign --fake I am not sure if it did some wrong thing, so now running python manage.py migrate campaign was not creating tableSo what solved for me is--
in mysql shell run
select * from django_migrations; Note the id of last migration which is creating problem in my case it was 62delete from django_migrations where id = 62Now I ran the migration again, and it worked this time. with command python manage.py migrate campaign i.e. required table was created as a result of applying migration
The problem I discovered working with Postgres is that I had not set the schema. I the original question is one of those gotchas that may have a number of different answers, so if the other answers are not working for you just check this.
The "problem" is that Postgres has an additional "namespace" layer which means you can specify the database but there can still be a whole set of tables, still in the same database, but in another schema or namespace.
The tables in this schema may be unreachable because the user being used to connect does not have permissions, or in fact the schema has been specified, but the tables were created in a different schema, or even you haven't specified the schema this time and are looking in the public schema while the tables have been created in another schema.
So the solution is to set the schema correctly, to what you intend, in every location and place that you use it. This boils down to correct database settings in all the settings files you are using, and logging in to the right schema and user when you inspect the database manually.
For example:
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.postgresql_psycopg2',
'OPTIONS': {'options': f'-c search_path={"foobar"}'},
'NAME': 'foo',
'USER': 'bar',
'PASSWORD': 'barpass',
'HOST': 'baz.example.com',
'PORT': 5432,
},
}
The database name here is foo, the username is bar and the schema name is foobar. Adding this line to the OPTIONS parameter defaults the schema for all operations.
For other usage, within Postgres, you can display the current search_path, and alter it for the current session, or "permanently" for the database:
SHOW search_path;
SET search_path=foobar,public;
ALTER DATABASE foo SET search_path TO foobar;
If your problem was that Django was creating your tables, but just in the wrong schema or under different permissions, I hope this has resolved your issue.
This kind-of thing was happening to me when I would try to reset my DB. Nothing else would work to get django to recognize my tables except:
python manage.py migrate --run-syncdb
In my case those solutions didn't work to me
I have to:
Create a new app: py manage.py startapp new_app_name
Copy all the files in my new app
Run: py manage.py makemigrations
Run: py manage.py migrate
It works to me, I hope it could be useful for you too
Below commands worked for me
python manage.py makemigrations app_name
python manage.py migrate app_name
I had the same issue and lol I just forgot to change my engine to the needed one

django.db.utils.ProgrammingError: relation already exists

I'm trying to set up the tables for a new django project (that is, the tables do NOT already exist in the database); the django version is 1.7 and the db back end is PostgreSQL. The name of the project is crud. Results of migration attempt follow:
python manage.py makemigrations crud
Migrations for 'crud':
0001_initial.py:
- Create model AddressPoint
- Create model CrudPermission
- Create model CrudUser
- Create model LDAPGroup
- Create model LogEntry
- Add field ldap_groups to cruduser
- Alter unique_together for crudpermission (1 constraint(s))
python manage.py migrate crud
Operations to perform:
Apply all migrations: crud
Running migrations:
Applying crud.0001_initial...Traceback (most recent call last):
File "manage.py", line 18, in <module>
execute_from_command_line(sys.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 385, in execute_from_command_line
utility.execute()
File "/usr/local/lib/python2.7/dist-packages/django/core/management/__init__.py", line 377, in execute
self.fetch_command(subcommand).run_from_argv(self.argv)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 288, in run_from_argv
self.execute(*args, **options.__dict__)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/base.py", line 338, in execute
output = self.handle(*args, **options)
File "/usr/local/lib/python2.7/dist-packages/django/core/management/commands/migrate.py", line 161, in handle
executor.migrate(targets, plan, fake=options.get("fake", False))
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 68, in migrate
self.apply_migration(migration, fake=fake)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/executor.py", line 102, in apply_migration
migration.apply(project_state, schema_editor)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/migration.py", line 108, in apply
operation.database_forwards(self.app_label, schema_editor, project_state, new_state)
File "/usr/local/lib/python2.7/dist-packages/django/db/migrations/operations/models.py", line 36, in database_forwards
schema_editor.create_model(model)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 262, in create_model
self.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/schema.py", line 103, in execute
cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 82, in execute
return super(CursorDebugWrapper, self).execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 66, in execute
return self.cursor.execute(sql, params)
File "/usr/local/lib/python2.7/dist-packages/django/db/utils.py", line 94, in __exit__
six.reraise(dj_exc_type, dj_exc_value, traceback)
File "/usr/local/lib/python2.7/dist-packages/django/db/backends/utils.py", line 66, in execute
return self.cursor.execute(sql, params)
django.db.utils.ProgrammingError: relation "crud_crudpermission" already exists
Some highlights from the migration file:
dependencies = [
('auth', '0001_initial'),
('contenttypes', '0001_initial'),
]
migrations.CreateModel(
name='CrudPermission',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('_created_by', models.CharField(default=b'', max_length=64, null=True, editable=False, blank=True)),
('_last_updated_by', models.CharField(default=b'', max_length=64, null=True, editable=False, blank=True)),
('_created', models.DateTimeField(null=True, editable=False, blank=True)),
('_last_updated', models.DateTimeField(null=True, editable=False, blank=True)),
('domain', models.CharField(max_length=32, choices=[(b'town', b'Town'), (b'boe', b'BOE'), (b'police', b'Police')])),
('ldap_group', models.CharField(max_length=128, verbose_name=b'LDAP group')),
('can_add', models.BooleanField(default=False, verbose_name=b'add')),
('can_change', models.BooleanField(default=False, verbose_name=b'change')),
('restrict_change_to_own', models.BooleanField(default=False)),
('can_delete', models.BooleanField(default=False, verbose_name=b'delete')),
('restrict_delete_to_own', models.BooleanField(default=False)),
('models', models.ManyToManyField(to='contenttypes.ContentType', null=True, blank=True)),
],
options={
'verbose_name': 'CRUD permission',
},
bases=(models.Model,),
),
migrations.AlterUniqueTogether(
name='crudpermission',
unique_together=set([('ldap_group', 'can_add', 'can_change', 'can_delete', 'domain')]),
)
,
The crud app is not meant to actually do anything, but I use it another app, so when I try migrate from that app, I trigger the above problem.
I've found other examples on the web of people with similar issues, but none of their cases seem to apply because
The problem affects an entire relation, not just one column
I am not using multiple inheritance.
Where should I look next to find the underlying problem?
This works pretty fine
./manage.py migrate --fake default
https://docs.djangoproject.com/en/2.2/ref/django-admin/#cmdoption-migrate-fake
Do python manage.py migrate --fake initally.
https://docs.djangoproject.com/en/3.2/ref/django-admin/#django-admin-migrate
I've faced similar issue when added couple new fields to existing model. I'm using Django 1.9, which introduced --run-syncdb option. Running manage.py migrate --run-syncdb fixed my tables.
Now (I'm using Django 1.9) you can make:
./manage.py migrate [--database DATABASE] --fake [app_label] [migration_name]
This way you're targeting the problem with more accuracy, and you can fake only the problematic migration on the specific database.
So, looking at the question, you could:
./manage.py migrate --database default --fake crud crud.0001_initial
Been facing a similar issue, eventually deleted all .py files in migration folder (django 1.7 creates one automatically), worked perfectly after that.
I was facing the similar issues, where i had changed column name. I was getting same error as mentioned in the stack-trace provided with he question.
Here's what I did.
I ran fake migrations first. Then i removed it's(migrations i wanted to run) entry from django_migrations table and ran migrations again(no fake this time).
Changes appeared as expected for me.
hope this is helpful.
Django provides a --fake-initial option which I found effective for my use. From the Django Migration Documentation:
--fake-initial
Allows Django to skip an app’s initial migration if all database
tables with the names of all models created by all CreateModel
operations in that migration already exist. This option is intended
for use when first running migrations against a database that
preexisted the use of migrations. This option does not, however, check
for matching database schema beyond matching table names and so is
only safe to use if you are confident that your existing schema
matches what is recorded in your initial migration.
For my use, I had just pulled a project from version control and was preparing to add some new model fields. I added the fields, ran ./manage.py makemigrations and then attempted to run ./manage.py migrate which threw the error since, as one would expect, many of the fields already existed in the existing database.
What I should have done was to run makemigrations immediately after pulling the project from versions control to create a snapshot of existing models' state. Then, running the ./manage.py migrate --fake-initial would be the next step.
After that you can add away and makemigrations > migrate as normal.
NOTE: I do not know if a --fake-initial would skip existing fields and add new ones. I opted to comment out the new fields I'd created up to that point, run the --fake-initial as if it were the first thing I did after pulling from version control, then added in updated fields in the next migration.
Other related documentation: https://docs.djangoproject.com/en/dev/topics/migrations/#initial-migrations
In my case, a migration file was deleted and a new one was auto-generated, which had a different name. Because of the name difference, Django tried to apply the new migration file, which was exactly same as the previously applied one, which was now removed. In both of them, a new model had to be created which resulted in django.db.utils.ProgrammingError: relation "app_space" already exists. I tried to reverse the migration, but the missing migration file prevented django from actually reversing it. Lesson learnt, migration files should be checked into git.
Here are some steps that helped me to get to the bottom of this. --fake solved it temporarily but the same issue happened in the next migration. I wouldn't recommend --fake unless you know for sure it is the right use case for it.
This answer was really key for me.
Check previous migrations python manage.py showmigrations
Check applied migrations in Django DB select * from django_migrations; (use psql to access postgres db console: psql -h 0.0.0.0 -U <your-db-user> then use target db \c <your-db-name>).
I saw an applied migration that was no longer in my migrations folder.
20 | app | 0001_initial | 2021-03-05 07:40:20.14602+00
21 | app | 0002_some_auto_name | 07:40:20.269775+00
22 | app | 0003_auto_20210318_2350 <---here | 2021-03-18 23:50:09.064971+00
But in migrations folder I had 0003_auto_20210318_2355, the same file generated 5 minutes later. I renamed the migration file to the name above so that I could reverse it.
Reverse the migration by passing the migration to which you want to return.
python manage.py migrate <app-name> <latest-migration-to-which-to-return>
python manage.py migrate app 0002_some_auto_name
Do the right thing from here and check in the migrations to git. Then you can do makemigrations and migrate and have a more peaceful life.
For me, When I faced this exception, I solve it using the Django dbshell utility or any kind of MY_DATABASE Viewer / interactive command line.
DBShell:
python manage.py dbshell
ALTER TABLE [name_of_field_that_already_exists] DROP column [field_table];
I've been dealing with this for several years.
There could be different scenarios:
Scenario 1: as in the original post, you had no tables to start with.
In this case, I'd
comment out the relationship in models.py
run python manage.py
migrate assuming that it now succeeds
uncomment what you
commented out in step 1 run python manage.py migrate --fake
Scenario 2: multiple apps:
One possibility is that you might have different apps and the data model of one app is using some tables from the other app. In this case, if the data model is designed properly, you should be able to create the tables for one app only (by specifying only that one in setting.py), then add the other app and migrate. If it is not design with care, and there are recursive dependencies, I suggest changing the design rather than making a temporary fix.
Scenario 3: you had some tables and something went wrong with your migration, then I'd
revert models.py to what it was and only introduce the new
relationship that appears to already exist in models.py.
delete migration folder
run python manage.py makemigrations
introduce new changes to models.py if any and continue with makemigrations and
migrate commands as usual.
I found and solved a particular example of this error in a Django 1.10 project while I was changing a foreign key field named member to point to a different table. I was changing this in three different models and I hit this error on all of them. In my first attempt I renamed member to member_user and tried to create a new field member as a foreign key pointing at the new table, but this didn't work.
What I found is that when I renamed the member column it did not modify the index name in the form <app>_<model>_<hash> and when I tried to create a new member column it tried to create the same index name because the hash portion of the name was the same.
I resolved the problem by creating a new member_user relation temporarily and copying the data. This created a new index with a different hash. I then deleted member and recreated it pointing at the new table and with it the would-be conflicting index name. Once that was done I ran the RunPython step to populate the new member column with references to the applicable table. I finished by adding RemoveField migrations to clean up the temporary member_user columns.
I did have to split my migrations into two files because I received this error:
psycopg2.OperationalError: cannot ALTER TABLE "<table_name>" because it has pending trigger events
After the creation and copy of data into member_user I was not able to remove member in the same migration transaction. This may be a postgres specific limitation, but it was easily resolved by creating another transaction and moving everything after creating and copying member_user into the second migration.
I found this problem in web2pyframework in models/config.py .
Change
settings.base.migrate = True
on config file to
settings.base.migrate = False
Problem solved.
I recently had the same issue and tried some of the solutions here. manage.py migrate --fake led to a "django_content_type" does not exist error. Equally deleting old migrations might cause problems for other users if the migrations are shared.
The manage.py squashmigrations command (docs) seems to be the ideal way to deal with this. Condenses old migrations into a single migration (which prevents applying them out of sequence etc), and preserves the old migrations for any other users. It worked in my case at least.
I am not sure about using the solution with fake. Most likely that error will occur again at the next migration.
Find out which columns are creating that problem
python manage.py dbshell
select * from <tablename> where false;
(Now you see which columns are saved by postgresql and can delete them in the database)
alter table <tablename> drop column <columnname>;
(Start the migrations process)
python manage.py makemigrations
python manage.py migrate
If you're getting this error when you run python manage.py test --k, you can fix it by deleting the test database: python manage.py test
I had the same problem.
./manage.py migrate --fake is not an option, expecially when it is your first commit. When you run ./manage.py makemigrations it collects a migration file and if it is the first mention of your model in code, then django will try to create such table in DB. To cure it, you should:
Remove migrations.CreateModel operations from your migration file
Run ./manage.py migrate in console
Ctrl+z your changes in mogrations file
Very Easy Solution
TLDR:
Comment out the fields in your migration file that are seen in the already exists error. Then run
python manage.py migrate
Uncomment the fields in the migration files after the migration has successfully run and bam, THAT'S IT.
Django now skips all the fields that already exist in your Database, and just adds the new ones.
That is probably because you have renamed the model property or did not run full migration before.
Use your magic SQL skills to delete the table (or rename it if it's prod) and run the migration.
Remember to make sure that full migration files are consistent and can deploy on a fresh and empty DB.
Do not try to use --fake, because with this you risk corrupting your database.
Instead, you can backup your current database, recreate it, and then apply backup.
Create backup: pg_dump -F c -v -h localhost <database_name> -f tmp/<pick_a_file_name>.psql
Recreate it: rails db:drop db:create
Restore backup: pg_restore --exit-on-error --verbose --dbname=<database_name> tmp/<pick_a_file_name>.psql

python manage.py migrate landing error

I want to migrate my app "landing" with south I write the following command
python manage.py migrate landing
but it shows the following error
Running migrations for landing:
Migrating forwards to 0003_auto__chg_field_userinput_email2.
landing:0001_initial
FATAL ERROR - The following SQL query failed: CREATE TABLE landing_userinput (
id integer AUTO_INCREMENT NOT NULL PRIMARY KEY, name varchar(120) NOT NULL,
email varchar(200) NOT NULL, city varchar(120) NOT NULL, timestamp datetim
e NOT NULL)
The error was: (1050, "Table 'landing_userinput' already exists")
! Error found during real run of migration! Aborting.
! Since you have a database that does not support running
! schema-altering statements in transactions, we have had
! to leave it in an interim state between migrations.
! You might be able to recover with: = DROP TABLE landing_userinput CASCAD
E; []
raise errorclass, errorvalue
django.db.utils.OperationalError: (1050, "Table 'landing_userinput' already exists")
Please give me suggestions to improve this bug.
Don't use syncdb and migrate at the same time; this will conflict as the initial migration will create a blank table.
If you have a new app and want to have it managed by south, your sequence of operations is:
./manage.py schemamigration landing --initial -- this creates the initial migration, which creates the tables for the application. You only do this once.
./manage.py migrate landing -- this will apply the migration. The first time you do this (with step #1 from above), this will create an empty table in the database.
Once you have done the first two steps, whenever you make a change to your model, you run these two commands:
./manage.py schemamigration landing --auto -- this will create the file that has the changes to your model (the migration).
./manage.py migrate landing -- this will apply the new migration (this is the same command from above); and it will affect the changes to your database.
If you already have an existing application, install south and run syncdb to create south's own database tables, then run ./manage.py convert_to_south yourappname; this will do a "fake" migration and set it to the last state of the models. Then, follow the schemamigration yourappname --auto and migrate steps.
In your case, you have two options:
Drop the table (as the error suggests). This will get rid of all the data as well. If you are in development, this is the easiest way to get started fresh (you should also use fixtures if you want to provide some default data for your models).
You can use the --fake option to trick south into thinking the operation has been done already. See the documentation for more.

Categories