95

I use Django1.7 with Mezzanine. I create simple profile (according to Mezzanine documentation) stored in separate app "profiles":

class RoadmapProfile(models.Model):
    user = models.OneToOneField("auth.User")
    fullname = models.CharField(max_length=100, verbose_name="Full name")

Creation of migrations returns:

  Migrations for 'profiles':
      0001_initial.py:
        - Create model RoadmapProfile

When I run "migrate profiles":

Operations to perform:
  Apply all migrations: profiles
Running migrations:
  No migrations to apply.

The issue is, when I try to open any page related to mezzanine.accounts (for example update account), it crashes with:

OperationalError at /accounts/update/

no such column: profiles_roadmapprofile.fullname

What I have done wrong?

matousc
  • 3,698
  • 10
  • 40
  • 65
  • 1
    Flow of migration is like: `python manage.py makemigrations ` --> `python manage.py migrate` – ruddra Sep 21 '14 at 11:42
  • 9
    yes, that is what I have done. – matousc Sep 21 '14 at 11:52
  • 2
    Note that most of the answers here are pretty bad especially if you're dealing with a production database. Make sure you understand the suggestion before tinkering. – karuhanga Feb 09 '22 at 08:49

23 Answers23

152
  1. In MySQL Database delete row 'profiles' from the table 'django_migrations'.
  2. Delete all migration files in migrations folder.
  3. Try again python manage.py makemigrations and python manage.py migrate command.
Zulfugar Ismayilzadeh
  • 2,643
  • 3
  • 16
  • 26
  • 1
    @LuísdeSousa No, it should not, because I have tried that and it does not help at all. – matousc Apr 09 '15 at 09:14
  • 7
    An answer with "delete all files" in it should be done carefully and sometimes we just can't/don't want to delete everything. – Patrick Bassut Jul 02 '15 at 07:06
  • if only there would have been and oscar / nobel for tech work....u sir....deserved it 10 years in row!! :) – NoobEditor Nov 08 '16 at 05:50
  • Just so you know `DELETE from django_migrations;` is the command to clear the mysql table. – Timothy Leung Jan 30 '17 at 23:15
  • After doing this, migrations not working at all, caused some other error. Now have to drop all tables and run migrations again to resolve this. Be careful! – Lovepreet Singh Aug 24 '17 at 12:10
  • 6
    I'd highly suggest to check your migrations first. SELECT * FROM django_migrations; Here you'll get a list with all migrations. Take the id, and run DELETE FROM django_migrations WHERE django_migrations.id in (id2, id2 .... idN) – Wolfgang Leon Sep 05 '18 at 18:42
  • now I get this error when running migrate: relation "django_content_type" already exists – CYW Apr 25 '23 at 05:46
94

I am a Django newbie and I was going through the same problem. These answers didn't work for me. I wanted to share how did I fix the problem, probably it would save someone lots of time.

#Situation: I make changes to a model and I want to apply these changes to the DB.

###What I did: Run on shell:

python manage.py makemigrations app-name
python manage.py migrate app-name

###What happened:

  • No changes are made in the DB

  • But when I check the db schema, it remains to be the old one

###Reason:

  • When I run python manage.py migrate app-name, Django checks in django_migrations table in the db to see which migrations have been already applied and will skip those migrations.

#What I tried: Delete the record with app="my-app-name" from that table (delete from django_migrations where app = "app-name"). Clear my migration folder and run python manage.py makemigration my-app-name, then python manage.py migrate my-app-name. This was suggested by the most voted answer. But that doesn't work either.

###Why? Because there was an existing table, and what I am creating was a "initial migration", so Django decides that the initial migration has already been applied (Because it sees that the table already exists). The problem is that the existing table has a different schema.

##Solution 1:

Drop the existing table (with the old schema), make initial migrations, and applied again. This will work (it worked for me) since we have an "initial migration" and there was no table with the same name in our db. (Tip: I used python manage.py migrate my-app-name zero to quickly drop the tables in the db)

Problem? You might want to keep the data in the existing table. You don't want to drop them and lose all of the data.

##Solution 2:

  1. Delete all the migrations in your app and in django_migrations all the fields with django_migrations.app = your-app-name How to do this depends on which DB you are using Example for MySQL: delete from django_migrations where app = "your-app-name";

  2. Create an initial migration with the same schema as the existing table, with these steps:

  • Modify your models.py to match with the current table in your database (Here, use the command "python manage.py inspectdb". This command is like reverse migration. It generates the corresponding models.py for the current database tables schema.)

  • Delete all files in "migrations"

  • Run python manage.py makemigrations your-app-name

  • If you already have an existing database then run python manage.py migrate --fake-initial and then follow the step below.

  1. Modify your models.py to match the new schema (e.i. the schema that you need now)

  2. Make new migration by running python manage.py makemigrations your-app-name

  3. Run python manage.py migrate your-app-name

This works for me. And I managed to keep the existing data.

#More thoughts: The reason I went through all of those troubles was that I deleted the files in some-app/migrations/ (the migrations files). And hence, those migration files and my database aren't consistent with one another. So I would try not modifying those migration files unless I really know what I am doing.

Abhishek
  • 3
  • 2
phanhuy152
  • 1,343
  • 12
  • 11
  • 1
    Good thinking. I have the same error, tried this approach but this just results in me getting a lot of errors, e.g. `sqlite3.OperationalError: table "django_content_type" already exists`. The problem is that for some reason, it is trying to recreate tables that already exist. My problem is that only one of these it's trying to create are missing. I guess I will have to delete the database and start over. Very frustrating that django doesn't handle changes properly, even if one deletes the migration files, the migrations in the database. It should work. – CoderGuy123 Aug 08 '16 at 01:34
  • 2
    This was by far the clearest answer. Solution 2 worked for me. – Brandon Bertelsen Dec 02 '16 at 05:40
  • 1
    One thing: if I have a `model.py` with several models, like `MA` and `MB`, and I want to apply changes to `MA`; now, with this solution, which is the best till now, when I migrate Django will complain: `Table 'MB' already exists.`, which is obvious because we didn't drop `MB` table in the process of realignment. So, any solution? Thanks, your solution works in most of the times. – WesternGun Apr 12 '18 at 14:45
  • 1
    So, at last I find the answer: you must mark other models in the same `models.py` to be `managed=False`. So the code would be: `class Meta: managed=False` in other models. – WesternGun Apr 12 '18 at 14:59
  • thanks everything is gone now, I have django.db.utils.ProgrammingError: column "name" of relation "django_content_type" does not exist – nassim Jun 08 '21 at 20:47
  • `delete from django_migrations where app = "app-name"` <-- this command helped me. Thanks – Vikas Bansal Sep 02 '21 at 12:10
44

Sounds like your initial migration was faked because the table already existed (probably with an outdated schema):

https://docs.djangoproject.com/en/1.8/topics/migrations/#adding-migrations-to-apps

"This will make a new initial migration for your app. Now, when you run migrate, Django will detect that you have an initial migration and that the tables it wants to create already exist, and will mark the migration as already applied."

Otherwise you would get an no-such-table error :)

Did you clean up the applied-migrations table? That's also a common cause for non-applied migrations.

ACimander
  • 1,852
  • 13
  • 17
  • Ok, I deleted migrations folder in application and run `python manage.py sqlclear profiles`. After that I used makemigrations and migrate for the app again - same result. What more I should do? – matousc Sep 21 '14 at 13:47
  • Did you delete the profiles_roadmapprofile table in your database before running the migration? If not the initial migration will just get auto-applied again :) (Django only checks your models and migration files and fails to notice that the existing table has a divergent schema) – ACimander Sep 21 '14 at 14:16
  • It returns to me: BEGIN; DROP TABLE "profiles_roadmapprofile"; COMMIT;`So I suppose it is deleted – matousc Sep 21 '14 at 14:22
  • 1
    If I'm not mistaken sqlclear just prints the SQL statement but does not execute it, thus leaving your rogue table untouched. – ACimander Sep 21 '14 at 14:33
  • you are correct, it just print the SQL statement. I deleted table manually and now it works. – matousc Sep 22 '14 at 13:08
  • I was able to work around this by removing the line from my last migration and then making the migrations and migrating them. Though I already new that the table was not in my database before I did this. – SudoKid Feb 05 '16 at 18:42
  • Thanks for the edit 'clean up the applied-migrations table'. Removing last applied migration solved my issue. – Vladimir Dmi Dec 18 '17 at 12:52
  • the link is broken – Lorenzo Lerate Jul 26 '21 at 19:26
22

1- run python manage.py makemigrations <appname>

2- run python manage.py sqlmigrate <appname> <migrationname> - you will find migrationname in migration folder under appname (without '.py' extension of course)

3- copy all text of result # all sql commands that generated
4- go to your db ide and paste as new query and run it

now all changes are applied on your db

andilabs
  • 22,159
  • 14
  • 114
  • 151
masood
  • 725
  • 8
  • 23
  • 1
    but be aware it might be dirty way of running your django migrations and db environment. – andilabs Mar 01 '16 at 13:17
  • Dude I Love u. You r the dude..my saviour!! This is exactly what i wanted! Cheers man. This should get maximum votes. sqlmigrate is the command :) – Shashank Hegde Oct 15 '16 at 04:18
  • Once u get the ouput of sqlmigrate, run the sql queries just one by one . It fixes the problem. – Shashank Hegde Oct 15 '16 at 04:27
  • This fixed my issue. Thanks dude. – Temi 'Topsy' Bello Nov 14 '16 at 10:24
  • In my particular circumstances--- I did some squirrelly stuff--- it was necessary to add the `--database=` option to the end of the `sqlmigrate` command. Otherwise there was no printout. Also, you can simply pipe the output to `dbshell` as: `python manage.py sqlmigrate --database= | python manage.py dbshell --database=`. – Mike O'Connor Nov 19 '16 at 06:37
  • this will create tables. Will these tables then be empty? – Timo Dec 16 '17 at 20:35
  • I'm wary of future problems with this method, but it was the only thing I have found that will solve this problem. – Lawrence DeSouza Apr 16 '19 at 15:46
  • this is the best answer........It should be at top. – Chaitanya Mogal Nov 06 '20 at 08:05
  • it will apply the changes on your database. But, actually it wont be a migration itself. That is, it solves the issue for now, but not in totally. You will need to do it everytime a change is done on database – Programadores Brasil May 19 '21 at 16:42
22
python manage.py migrate --fake APPNAME zero

This will make your migration to fake. Now you can run the migrate script

python manage.py migrate APPNAME

Tables will be created and you solved your problem.. Cheers!!!

Vignesh
  • 1,521
  • 1
  • 12
  • 11
  • Broke all my migrations. The field deployment.Deployment.client was declared with a lazy reference to 'client.client', but app 'client' isn't installed. – Paul Kenjora May 23 '18 at 05:29
  • 1
    Make sure you have removed all the tables from db and also you have to make migration before you run these two lines of code. Thank you – Ishwor Khanal Dec 28 '19 at 23:34
12

In my case I wrote like this:

python manage.py makemigrations --empty yourappname

python manage.py migrate yourappname

or:

Django keeps track of all the applied migrations in django_migrations table. So just delete all the rows in the django_migrations table that are related to you app like:

DELETE FROM django_migrations WHERE app='your-app-name'

and then do:

python manage.py makemigrations python manage.py migrate

Leonardo Ramos
  • 313
  • 3
  • 7
  • note that if your migrations are not idempotent, which is the case most if the time, this would make the problem worse if the ones you delete were indeed applied. – karuhanga Feb 09 '22 at 08:47
5

The problem here are fake migrations somewhere. Basically in your database the table created from your model doesn't exist, tho somewhere in time that table existed before, due an old update o whatever it may be. The problem is that django already made those migrations so the tables MUST exist for hence overlooking migrations but getting error "table_doesnt_exist" in Admin.

Solution:

1.- Make sure to save any data from that model.

2.- Access your database and run this query.

 SELECT * FROM django_migrations;

3.- Get the id from the list generated from the query. These are migrations that Django has migrated so far, hence TABLES MUST EXIST. In your case I'd look for a row named roadmapprofile, due this is the name of your model.

4.- Now lets delete this row from this table using the ids,

 DELETE FROM django_migrations where django_migrations.id in (value_id1, value_id2 ... value_idN);

Replace value_id1 and value_id2 with respective ids. It could be only one or many so don't worry if you don't see more than 1 id, what this means is that only one model exists under the current app.

5.- Migrate app to zero

 manage.py migrate <app_name> zero

6.- Delete all migrations files within the app migrations folder

7.- Create Migrations

 manage.py makemigrations

8.- Once you delete these registries and run manage.py migrate; Django will be forced to run migrations for these models due "MIGRATIONS WON'T EXIST" for these models.

 manage.py migrate

That's it. You shouldn't have any problems following these instructions. By the way, you shouldn't loose any data from other models due you're only migrating and updating tables related to these specific models.

Wolfgang Leon
  • 695
  • 9
  • 20
5

This is a very confusing topic. django stores all applied migrations in a table called django_migrations. perform this sql ( i am using postgres . so in query tool section)

select * from django_migrations where app='your appname'  (app in which u have issue with).

This will list all applied migrations for that app.
Go to your app/migration folder and check all migrations . find the migration file associated with your error . file where your table was created or column added or modified.
look for the id of this migration file in django_migrations table( select * from django_migrations where app='your app') .

Then do :

delete from django_migrations where id='id of your migration';

delete multiple id's if you have multiple migrations file associated with your issue.

now reapply migrate

Python manage.py migrate yourappname

second option

  1. Drop tables in your app where you have issue.

  2. delete all migrations for that app from app/migrations folder.(don't delete init.py from that folder).

  3. now run

    python manage.py makemigrations appname

  4. now run

python manage.py migrate appname

2

My issue was that there was no __init__.py file in the same folder as the migrations. On adding the __init__.py to the folder which contained them, manage.py migrate found and ran them.

Eosis
  • 548
  • 1
  • 4
  • 12
2

The same problem happened to me using PostgreSQL I cleared all migrations in migrations folder and in migrations cache folder, and then in my PGADMIN ran:

delete from django_migrations where app='your_app'
Guillermo Zooby
  • 582
  • 2
  • 15
  • 32
1

Two steps:

1.to go database:

 DROP TABLE django_migrations;

2.remove all the migration files in migrations folder ,and then do makemigrations and migrate again

William
  • 3,724
  • 9
  • 43
  • 76
1

i solved it after hours research delete the app and create it again using python manage.py startapp your app name then register on the setting.py

habesha
  • 11
  • 2
0

@phanhuy152 has the best answer. Just to add my two cents:

His solution is:

  1. Delete migration history in DB
  2. Delete migrations folder
  3. Edit your model to be consistent with DB before your change
  4. makemigrations to restore the initial state of the migration files
  5. Then, change the model as you like
  6. makemigrations again
  7. migrate to apply updates to table.

But in my case, I have several models in the models.py file and at the last step, Django complains about Table xxx already exists, because the initial migrations files intends to create the xxx table again, when we just don't (and don't want to)drop other tables.

In this case, in order to preserve the data, we must tell Django to leave them alone in migrate. We just do: (assume that class A is the one we change, and class B, C remain same):

models.py:

from django.db import models

class A(models.Models):
    ...

class B(models.Models):
    class Meta:
        managed = False   # tell Django to leave this class alone

    ...

class C(models.Models):
    class Meta:
        managed = False   # tell Django to leave this class alone

Add these lines after we construct the initial migrations.

So, the process now is:

  1. ...
  2. ...
  3. ...
  4. ...
  5. Add managed = False to other classes
  6. makemigrations to apply Meta changes. You will see something like:

output:

Migrations for 'backEnd':
  backEnd/migrations/0002_auto_20180412_1654.py
    - Change Meta options on toid
    - Change Meta options on tprocessasinc
    - Change Meta options on tservers
    - Change Meta options on tsnmpserver
  1. migrate to apply them in DB
  2. Change your model now: add a field, change the type, etc.
  3. migrate again.
  4. Delete the Meta class to let Django manage other class again. makemigrations, migrate again.

Now you have all the structure and data of your models, without losing the part formerly stored in DB.

WesternGun
  • 11,303
  • 6
  • 88
  • 157
0

I had this same problem. Make sure the app's migrations folder is created (YOURAPPNAME/ migrations). Delete the folder and enter the commands:

python manage.py migrate --fake
python manage.py makemigrations <app_name>
python manage.py migrate --fake-initial

I inserted this lines in each class in models.py:

class Meta:
    app_label = '<app_name>'

This solved my problem.

0

For me, none of the offered solutions worked. It turns out that I was using different settings for migration (manage.py) and running (wsgi.py). Settings defined in manage.py used a local database however a production database was used in wsgi.py settings. Thus a production database was never migrated. Using:

django-admin migrate

for migration proved to be better as you have to specify the settings used as here.

  • Make sure that when migrating you always use the same database as when running!
0

Maybe your model not linked when migration process is ongoing. Try to import it in file urls.py from models import your_file

Serg Smyk
  • 613
  • 5
  • 11
0

if you are using GIT for control versions and in some of yours commit you added db.sqlite3, GIT will keep some references of the database, so when you execute 'python manage.py migrate', this reference will be reflected on the new database. I recommend to execute the following command:

git filter-branch --index-filter "git rm -rf --cached --ignore-unmatch 'db.sqlite3' HEAD

it worked for me :)

jizhihaoSAMA
  • 12,336
  • 9
  • 27
  • 49
gianlop3z
  • 107
  • 2
  • 9
0

The pb with the solutions is that you must delete your data. If you want to avoid that + you are using Sqlite , follow the process:

  1. Download SQLITEStudio
  2. Open SqliteStudio, and link it to you project db
  3. click on the table you wish to modify, and add column ( same as in your model)
pierre
  • 1
0

All I did was delete the last line of the django-migrations table. It was clear this was the right migration to delete because its name was the same as the migration I generated but could not apply.

dmc85
  • 250
  • 1
  • 9
0

I had the same issue with postgress , deleting django_migrations database solved the issue

enter image description here

Mohamed MosȜd
  • 138
  • 2
  • 8
0

I had this problem few hours ago. For me, my migration folder was outside my app so I was unable to run any migrations as Django keeps saying No changes made. Moving the migration folder under my API app worked for me.

0

Make sure to register your model in admin.py if you haven't:

from .models import RoadmapProfile

admin.site.register(RoadmapProfile)

then migrate:

python manage.py makemigrations profile
python manage.py migrate

If this still doesn't fix the issue, you may want to fake a migration.

python manage.py migrate --fake
Meraj al Maksud
  • 1,528
  • 2
  • 22
  • 36
0

If you execute the migrate command again and there are no unapplied migrations, the command will output the following:

Operations to perform: Apply all migrations: admin, auth, blog, contenttypes, sessions, users Running migrations: No migrations to apply.

To list the project migrations and their status, you use the showmigrations command:

python manage.py showmigrations