31👍
Deleting the migration directory is never a good idea, because Django then loses track of which migration has been applied and which not (and once an app is deployed somewhere it can become quite difficult to get things back in sync).
Disclaimer: whenever things like that occur it is best to backup the database if it contains anything valuable. If in early development it is not necessary, but once things on the backend get out of sync there is a chance of things getting worse. 🙂
To recover, you could try resetting your models to match exactly what they were before you have added/removed the fields. Then you can run
$ python manage.py makemigrations myproj
which will lead to an initial migration (0001_initial...
). Then you can tell Django to fake that migration, which means to tell it to set its internal counter to this 0001_initial
:
With Django 1.7:
$ python manage.py migrate myproj
With Django >= 1.8:
$ python manage.py migrate myproj --fake-initial
Now, try to change your model and run makemigrations
again. It should now create a 0002_foobar
migration that you could run as expected.
41👍
Make sure that the migrations/
folder contains a __init__.py
file
Lost half an hour over that.
- [Django]-Django Celery – Cannot connect to amqp://guest@127.0.0.8000:5672//
- [Django]-Create a field whose value is a calculation of other fields' values
- [Django]-VSCode terminal shows incorrect python version and path, launching terminal from anaconda works perfectly
18👍
In my case, the migrations were not being reflected in mysql database. I manually removed the row of ‘myapp'(in your case ‘myproj’) from the table ‘django_migrations’ in mysql database and ran the same commands again for migration.
- [Django]-Compare TinyMCE and CKeditor for a Wiki
- [Django]-Django Aggregation: Summation of Multiplication of two fields
- [Django]-TypeError: login() takes 1 positional argument but 2 were given
11👍
Most of the above solutions would help in the issue, however, I wanted to point out another possible (albeit rare) possibility that the allow_migrate
method of database router may be returning False
when it should have returned None
.
Django has a setting DATABASE_ROUTERS
which will be used to determine which database to use when performing a database query.
From the docs:
if you want to implement more interesting database allocation behaviors, you can define and install your own database routers.
A database router class implements up to four methods:
- db_for_read(model, **hints)
- db_for_write(model, **hints)
- allow_relation(obj1, obj2, **hints)
- allow_migrate(db, app_label, model_name=None, **hints)
From the documentation:
allow_migrate(db, app_label, model_name=None, **hints)
Determine if the migration operation is allowed to run on the database with alias db. Return True if the operation should run, False if it shouldn’t run, or None if the router has no opinion.
It is possible that one of the database routers in sequence is returning False for the migration that you’re trying to run, in which case the particular operation will not be run.
- [Django]-Get path of virtual environment in pipenv
- [Django]-Django TypeError: get() got multiple values for keyword argument 'invoice_id'
- [Django]-Difference between different ways to create celery task
6👍
I find Django migrations a bit of a mystery, and tend to prefer external tools (liquibase, for example).
However, I just ran into this “No migrations to apply” problem as well. I also tried removing the migrations
folder, which doesn’t help.
If you’ve already removed the migrations
folder, here’s an approach that worked for me.
First, generate the new “clean” migrations:
$ python manage.py makemigrations foo
Migrations for 'foo':
dashboard/foo/migrations/0001_initial.py
- Create model Foo
- Create model Bar
Then look at the SQL and see if it looks reasonable:
$ python manage.py sqlmigrate foo 0001
BEGIN;
--
-- Create model Foo
--
CREATE TABLE "foo" ("id" serial NOT NULL PRIMARY KEY, ... "created_at" timestamp with time zone NOT NULL, "updated_at" timestamp with time zone NOT NULL);
CREATE INDEX "..." ON "foo" (...);
COMMIT;
Then apply execute that same SQL on your database.
I’m using Postgres but it will be similar for other engines.
One way is to write the content to a file:
$ python manage.py sqlmigrate foo 0001 > foo.sql
$ psql dbname username < foo.sql
BEGIN
CREATE TABLE
CREATE INDEX
COMMIT
Another is pipe the SQL directly:
$ python manage.py sqlmigrate foo 0001 | psql dbname username
Or copy and paste it, etc.
- [Django]-Django – view sql query without publishing migrations
- [Django]-Use Django template tags in jQuery/Javascript?
- [Django]-Success_message in DeleteView not shown
3👍
pip install django-extensions
and add this in the install app of settings.py
INSTALLED_APPS = [
'django_extensions'
]
Then run
python ./manage.py reset_db
Then run migrations again
python manage.py makemigrations
python manage.py migrate
Now, run migrations for your installed apps
python manage.py makemigrations your_app_name
python manage.py migrtate your_app_name
Done! See Your Database…
- [Django]-Django site with 2 languages
- [Django]-Django admin file upload with current model id
- [Django]-Can't install via pip because of egg_info error
2👍
In addition to the other answers, make sure that in models.py, you have managed = True
in each table’s meta
- [Django]-Django Error u"'polls" is not a registered namespace
- [Django]-Manifest: Line: 1, column: 1, Syntax error on Chrome browser
- [Django]-Django Style: Long queries?
2👍
If you’ve deleted all migration files and tables, then do these steps:
- python manage.py makemigrations appname
- python manage.py migrate appname
- delete rows of that app from django_migrations table
- python manage.py migrate appname –fake-initial.
It worked for me.
- [Django]-How can I trigger a 500 error in Django?
- [Django]-Why does django ORM's `save` method not return the saved object?
- [Django]-Django – filtering on foreign key properties
1👍
You can remove your db
- python manage.py makemigrations
- python manage.py migrate
- python manage.py migrate –run-syncdb
and see your data base this is working 🙂
- [Django]-HTML – How to do a Confirmation popup to a Submit button and then send the request?
- [Django]-A QuerySet by aggregate field value
- [Django]-Vagrant + Chef: Error in provision "Shared folders that Chef requires are missing on the virtual machine."
1👍
I was facing a similar issue when trying to migrate my models after creating it in models.py
. The problem was that I had not registered the app name in the INSTALLED_APPS
list in settings.py
. The app name in my case was "core":
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'core'
]
After adding it to INSTALLED_APPS
, the migrations worked like usual:
python manage.py makemigrations
python manage.py migrate
- [Django]-How to configure X-Frame-Options in Django to allow iframe embedding of one view?
- [Django]-Django app works fine, but getting a TEMPLATE_* warning message
- [Django]-Django / Comet (Push): Least of all evils?
0👍
Similar to Andrew E above but with a few changes especially where you haven’t deleted the migrations folder in your quest to resolve the issue
1 – In your intact migration folder just examine the 000*.py files counting from the highest down to initial.py till you find the one where your Model is defined, say 0002_entry.py
2 – python manage.py sqlmigrate app-name 0002 > 0002_sql.txt to capture the SQL commands
3 – Edit this file to ensure there are no hard CR/LFs and the ALTER, CREATE INDEX commands are each on own single line
4 – Log into your DB (I have Postgres) and run these commands
- [Django]-Django cannot import name x
- [Django]-How to stop gunicorn properly
- [Django]-Django gives Bad Request (400) when DEBUG = False
0👍
In Database delete row myproj
from the table django_migrations
.
Delete all migration files in the migrations folder.
Then run python manage.py makemigrations
and python manage.py migrate
commands.
- [Django]-How to avoid AppConfig.ready() method running twice in Django
- [Django]-Django sort by distance
- [Django]-Page not found 404 on Django site?
0👍
I had the same problem even when i had the migrations folder.
So I tried tricking the migrations to run the initial migration again.
I altered a field in my model and then did a python manage.py makemigrations
to create a new migration.
Then copied the operations list in the 0001_initial.py and pasted it above the newly created migration operation started with 0002_….py
This is the final code I used:
operations = [
migrations.CreateModel(
name='Operator',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('deactive', models.BooleanField(default=False)),
('operator', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='operator', to=settings.AUTH_USER_MODEL)),
],
),
migrations.CreateModel(
name='Teams',
fields=[
('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='teams_owner', serialize=False, to=settings.AUTH_USER_MODEL)),
('operators', models.ManyToManyField(related_name='teams_opearators', through='teams.Operator', to=settings.AUTH_USER_MODEL)),
],
),
migrations.AddField(
model_name='operator',
name='team',
field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='team', to='teams.teams'),
),
migrations.RemoveField(
model_name='operator',
name='deactive',
),
]
Don’t forget to do the python manage.py migrate
to apply the migration.
Worked fine for me. Hope it helps 🙂
- [Django]-Access kwargs from a URL in a Django template
- [Django]-How to override the queryset giving the filters in list_filter?
- [Django]-How to get logged in user's uid from session in Django?