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.
Добавил в модель три необязательных поля, но manage.py makemigrations создаёт миграции типа CreateTable (последних трёх полей в таблице нет, ) вместо AlterTable или AlterField:
migrations.CreateModel(
name='InviteBonus',
fields=[
('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),
('total', models.DecimalField(verbose_name='u0421u0443u043cu043cu0430 u043fu043bu0430u0442u0435u0436u0430', max_digits=12, decimal_places=2)),
('use_date', models.DateField(verbose_name='u0414u0430u0442u0430 u043fu043bu0430u0442u0435u0436u0430')),
('line', models.PositiveIntegerField(null=True, verbose_name='u043bu0438u043du0438u044f', blank=True)),
('paid', models.BooleanField(default=False, verbose_name='u0412u044bu043fu043bu0430u0447u0435u043du043e')),
('five_per_period', models.BooleanField(default=False, verbose_name='u043fu044fu0442u044c u0437u0430 u043fu0435u0440u0438u043eu0434')),
('comment', models.CharField(max_length=100, verbose_name='u041au043eu043cu043cu0435u043du0442u0430u0440u0438u0439')),
('inviter', models.ForeignKey(related_name='invite_bonuses', default=None, verbose_name='u0423u0447u0430u0441u0442u043du0438u043a', to='accounts.TreeNode')),
('newbie', models.ForeignKey(related_name='awards', verbose_name='u043fu0440u0438u0433u043bu0430u0448u0451u043du043du044bu0439', blank=True, to='accounts.TreeNode', null=True)),
],
options={
'db_table': 'invite_bonuses',
'verbose_name': 'u0432u044bu043fu043bu0430u0442u0430 u043au043bu0438u0435u043du0442u0443 u0437u0430 u043fu0440u0438u0433u043bu0430u0448u0435u043du0438u0435',
'verbose_name_plural': 'u0432u044bu043fu043bu0430u0442u044b u043au043bu0438u0435u043du0442u0430u043c u0437u0430 u043fu0440u0438u0433u043bu0430u0448u0435u043du0438u044f',
},
bases=(models.Model,),
),
Что я делал:
— Удалял папку migrations
— Чистил таблицу django_migrations
Затем запускал
manage.py makemigrations
manage.py migrate - FAKED, потому что таблица уже есть, поэтому нужно делать добавление полей вместо создания таблицы
manage.py syncdb - Тоже ни о чём
Python 3, Django 1.8.5, Postgres
I have a model Sites
that has been working fine. I recently tried to add a field, airport_code, and migrate the data.
class Site(BaseModel):
objects = SiteManager()
name = models.CharField(max_length=200, unique=True)
domain = models.CharField(max_length=200, unique=True)
weather = models.CharField(max_length=10)
nearby_sites = models.ManyToManyField('self', symmetrical=False, blank=True)
users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True)
facebook = models.URLField(max_length=200)
twitter = models.URLField(max_length=200)
header_override = models.TextField(blank=True)
email_header_override = models.TextField(blank=True)
timely_site_tag_id = models.IntegerField()
timely_featured_tag_id = models.IntegerField()
timely_domain = models.CharField(max_length=255)
sitemap_public_id = models.CharField(max_length=255)
state = models.CharField(max_length=24)
airport_code = JSONField()
However, when I ran makemigrations
I got an error:
django.db.utils.ProgrammingError: column sites_site.airport_code does not exist
LINE 1: ..._site"."sitemap_public_id", "sites_site"."state", "sites_sit...
Of course, this doesn’t make sense, because the column obviously does not exist when I’m trying to create it within the migration.
I have seen many questions about this bug on Stack Overflow that are unanswered, or have a solution to manually create the migration file, or destroy and rebuild the database. This is not an okay solution.
tjati
5,7054 gold badges41 silver badges56 bronze badges
asked Nov 12, 2015 at 21:39
After you run makemigrations, be sure to go through the stack trace step by step.
In my case, I noticed it traced through a call to a Form contained within a forms.py in a completely different app, which happened to have a call to the model I was trying to create a new migration for.
Moving the Form class out of forms.py into the views.py fixed the issue.
answered Jul 21, 2016 at 4:46
NexusNexus
7396 silver badges12 bronze badges
3
This bug was resolved for me by commenting out the django debug toolbar from INSTALLED_APPS in settings.py. I am not sure why debug toolbar is the culprit, but after I commented it out, I was able to run makemigrations
and migrate
with no issue.
Hoping this helps someone, as I spent twelve hours trying to figure it out.
answered Nov 12, 2015 at 21:39
AlexAlex
7431 gold badge7 silver badges19 bronze badges
3
I ran into this issue as well and the answer by @Nexus helped. I thought I’d provide details of my specific case here for better illustrate the cause of the issue. It seems like a potential bug to me.
I have a model Brand
as follows:
class Brand(BaseModelClass):
name = CharField(max_length=256, unique=True)
website = ForeignKey(URL, on_delete=CASCADE, null=True, blank=True)
I was running a python manage.py makemigrations
after adding a Boolean
field as follows:
class Brand(BaseModelClass):
name = CharField(max_length=256, unique=True)
website = ForeignKey(URL, on_delete=CASCADE, null=True, blank=True)
trusted = Boolean(default=True)
When running the makemigrations
command, I recieved an error similar to OP’s:
django.db.utils.ProgrammingError: column appname_brand.trusted does not exist
Per @Nexus’ suggestion, I went through the stacktrace, line-by-line, assuming that it wasn’t some core issue with Django. As it turns out, in one of apps forms.py
file I had the following:
choices={(str(brand.id), brand.name) for brand in Brand.objects.all()}
The solution was to simply comment-out that line, run manage.py makemigrations
, then run manage.py migrate
. Afterwards, I uncommented the line and everything and my forms’ functionality worked just as before.
answered Dec 8, 2018 at 18:06
alphazwestalphazwest
3,3231 gold badge24 silver badges39 bronze badges
4
In my case, that was because I had a unique_together constraint that was set.
When I wanted to remove a field, the auto-generated migration tried to remove the field before removing the unique_together constraint.
What I had to do was manually move up the migrations.AlterUniqueTogether constraint in the migration file, so that django removes first the constraint before trying to remove the field.
I hope this can help someone.
answered Apr 30, 2018 at 9:17
darksiderdarksider
1,0302 gold badges14 silver badges20 bronze badges
2
Make sure you are not doing any queries when loading the application!, as eg. in:
class A:
field = fn_that_makes_query()
When running migrate
or makemigrations
, Django performs system checks, which loads the entire application, so if during this process any queries are made which use added/altered db fields you run into inconsitencies, because you are trying to access db fileds that are not there yet.
answered Aug 16, 2019 at 6:31
nveonveo
3611 gold badge2 silver badges8 bronze badges
1
I too got same issue when i executed a cmd like python manage.py makemigrations app1
.
I resolved my issue by commenting the custom orms which is running in another app2 under views.
Example:
inside app1
models.py
class ModelA(models.Model):
subject = models.CharField(max_length=1)
course = models.CharField(max_length=1)
inside app2
view.py
# obj = ModelA.object.all()
# get_subjct = [s.subject for s in obj]
So here i have commented above code and executed the makemigrations and migrate then uncommented.
Working fine…
answered Feb 5, 2020 at 6:07
santhosh_djsanthosh_dj
3854 silver badges10 bronze badges
0
I got the same problem (column not exist) but when I try to run migrate
not with makemigrations
-
Cause: I removed the migration files and replaced them with single pretending intial migration file 0001 before running the migration for the last change
-
Solution:
- Drop tables involved in that migration of that app (consider a backup workaround if any)
- Delete the rows responsible of the migration of that app from the table
django_migrations
in which migrations are recorded, This is how Django knows which migrations have been applied and which still need to be applied.
And here is how solve this problem:
-
log in as postgres user (my user is called posgres):
sudo -i -u postgres
-
Open an sql terminal and connect to your database:
psql -d database_name
-
List your table and spot the tables related to that app:
dt
-
Drop them (consider drop order with relations):
DROP TABLE tablename ;
- List migration record, you will see migrations applied classified like so:
id | app | name | applied
—+——+———+———+
SELECT * FROM django_migrations;
-
Delete rows of migrations of that app (you can delete by id or by app, with app don’t forget ‘quotes’):
DELETE FROM django_migrations WHERE app='your_app';
-
log out and run your migrations merely (maybe run makemigrations in your case):
python manage.py migrate --settings=your.settings.module_if_any
Note: it is possible that in your case will not have to drop all the tables of that app and not all the migrations, just the ones of the models causing the problem.
I wish this can help.
answered May 30, 2018 at 10:44
Run into this problem after the migration of my postgres database to a differnt server. Somehow I messed up the database and could not update my model with the new class UserProfile.
I solved the problem creating initial migration for existing schema:
- Empty the
django_migrations
table:delete from django_migrations;
with a commandDELETE FROM django_migrations WHERE app='my_app';
- For every app, delete its
migrations
folder:rm -rf <app>/migrations/
- Reset the migrations for the «built-in» apps:
python manage.py migrate --fake
- For each app run:
python manage.py makemigrations <app>
. Take care of dependencies (models with ForeignKey’s should run after their parent model). - Finally:
python manage.py migrate --fake-initial
Got it here: https://stackoverflow.com/a/29898483
PS I’m not sure that this was relevant to the resolution of the problem but, first, I dropped the table in postgresql that caused an error and commented out the UserProfile class in models.
in shell:
sudo -su postgres
psql databse_name
DROP TABLE table_name;
models.py:
#class UserProfile(models.Model):
#user = models.OneToOneField(settings.AUTH_USER_MODEL, unique=True, primary_key=True, on_delete=models.CASCADE, related_name='user_profile')
#avatar = ThumbnailerImageField(upload_to='profile_images', blank=True)
#country = models.CharField(max_length = 128)
answered Jan 26, 2017 at 15:00
bilbohhhbilbohhh
6831 gold badge6 silver badges16 bronze badges
I ran into this problem recently after upgrading to Django 1.11. I wanted to permanently address the issue so I wouldn’t have to comment / uncomment code every time I ran a migration on the table, so my approach:
from django.db.utils import ProgrammingError as AvoidDataMigrationError
try:
... do stuff that breaks migrations
except AvoidDataMigrationError:
pass
I rename the exception during import to AvoidDataMigrationError
so it’s clear why it’s there.
answered Nov 9, 2018 at 14:03
Jeff BauerJeff Bauer
13.8k9 gold badges51 silver badges73 bronze badges
Just now had the same error when I tried to migrate a SingletonModel to actually contain the necessary fields.
Reason for the error was that my Model A used some fields of this SingletonModel (as configurable values). And during instantation of model A during the migration process it obviously couldn’t guarantee that my migration was safe.
A colleague had a wonderful idea. Make the default value for the field a function call, and therefor lazy.
Example:
class A (models.Model):
default_value = models.DecimalField(default: lambda: SingletonModel.get_solo().value, ...)
So therefor, my advice:
Try and make the offending call (seen in stacktrace) a lazy one.
answered Jul 19, 2019 at 12:57
I got the same issue, here is my case:
in the app MyApp
I add a new field to the model:
class Advisors(models.Model):
AdvID = models.IntegerField(primary_key=True)
Name = models.CharField(max_length=200,null=False)
ParentID = models.IntegerField(null=True) # <--- the NEW field I add
so what I did is:
in the urls.py
of MyProject
, NOT MyApp
, comment out the url() linked to MyApp
and then do makemigrations
and migrate
everything goes well;
in MyApp/urls.py
file:
urlpatterns = [
url(r'^admin/', admin.site.urls, name='admin'),
url(r'^$', views.HomePage.as_view(),name='home'),
#comment out the following line, after migrate success, bring it back;
# url(r'^myapp/', include('myapp.urls',namespace='research')), <---
]
answered Dec 5, 2019 at 22:30
Cat_SCat_S
314 bronze badges
Late to the party, but there is some info I want to share. It helped me a lot!
I am using django-solo to store app config in database, and I got the same issue as Alex when adding new field to configuration model. Stacktrace pointed me to the line where I’m getting config from database: conf = SiteConfiguration().get_solo()
.
There is a closed issue for django-solo project on Github. The idea is to make model loading lazy (exactly as MrKickkiller pointed before).
So for modern Django version (in my case 3.0) this code works perfectly:
from django.utils.functional import SimpleLazyObject
conf = SimpleLazyObject(SiteConfiguration.get_solo)
answered Mar 9, 2020 at 10:51
Pantone877Pantone877
4966 silver badges15 bronze badges
Stuck into this issue recently.
In my case, I added a reference to a non-existing field in the code, then I came to the model file and added the new field, then tried to run makemigrations
command which thrown the above error.
So I went to the stack trace all the way up and found the newly added reference was the problem. commented that out, ran makemigrations
and voila.
answered Aug 21, 2018 at 20:13
ShobiShobi
10.1k6 gold badges43 silver badges80 bronze badges
In my case it happens because of my custom AdminSite
has MyModel.objects.filter
on application start
, i have disabled it for makemigrations
and migrate
database.
answered Nov 12, 2019 at 15:46
Serg SmykSerg Smyk
5833 silver badges11 bronze badges
I faced this problem. for solving problem follow the step.
1.open Database and table.
2.Create a required(sites_site.airport_codes in question ) column which was not exits in
your table with default value.
3.run the command
python manage.py makemigrations
python manage.py migrate <app name>
python manage.py runserver
answered Jul 8, 2020 at 13:51
Got the same issue, thanks to this thread to point me out the way by exploring the backtrace.
In a ListView declaration, I was declaring a queryset with a filter pointing to the model I was trying to update, without overiding the get_query_set() function.
class BacklogListView(ListView):
model = Version
context_object_name = 'vhs'
template_name = 'backlog_list.html'
queryset = VersionHistory.objects.filter(extract=Extract.objects.last())
fixed by:
class BacklogListView(ListView):
model = Version
context_object_name = 'vhs'
template_name = 'backlog_list.html'
def get_queryset(self):
queryset = VersionHistory.objects.filter(extract=Extract.objects.last())
If it can help someone…
answered Jan 8, 2021 at 15:58
You might have a RunPython using the new state of the model you need before modifying your database, to fix that, always use apps.get_model
def forwards_func(apps, schema_editor):
# We get the model from the versioned app registry;
# if we directly import it, it'll be the wrong version
SiteModel = apps.get_model('my_app', 'Site')
# DONT
from my_app.models import Site
def reverse_func(apps, schema_editor):
...
answered Jan 19, 2021 at 2:12
This issue happens when you try to migrate an app X which has a related attribute to an app Y before Y migrate.
So, to solve it you have to make the migrations of Y first.
You can specify the order migrations by using the django dependencies property
You can also, run:
python manage.py migrate --run-syncdb
then for every error caused app (like django.db.utils.ProgrammingError: relation "AppName_attribute" does not exist)
run:
python manage.py migrate AppName
P.S:
If you need to reset the db schema, you can use:
manage.py reset_schema
And don’t forget to remove all migrations files:
find . | grep -E "(__pycache__|.pyc|.pyo$|migrations)" | xargs rm -rf
answered Apr 1, 2021 at 13:21
Mahrez BenHamadMahrez BenHamad
1,7211 gold badge15 silver badges21 bronze badges
For my case i am getting the error when migrating. I solved the issue using the below steps.
After makemigration the created file was.
# Example:
class Migration(migrations.Migration):
dependencies = [
('app1', '0030_modify'),
]
operations = [
migrations.RemoveField(
model_name='users',
name='phone1',
),
migrations.RemoveField(
model_name='users',
name='phone2',
),
migrations.AlterUniqueTogether(
name='users',
unique_together={('email', 'phone')},
),
]
I solved the issue by moving the unique_together migration first, then field removals.
# Example:
class Migration(migrations.Migration):
dependencies = [
('app1', '0030_modify'),
]
operations = [
migrations.AlterUniqueTogether(
name='users',
unique_together={('email', 'phone')},
),
migrations.RemoveField(
model_name='users',
name='phone1',
),
migrations.RemoveField(
model_name='users',
name='phone2',
),
]
Hope it will solve your problem
answered Jul 9, 2021 at 8:50
Let us resolve any Django migration issue locally. Let us say you added a new field into the models.py
file which caused the migration failure. The reason for migration failure can be anything, maybe a bad state of the database, or failure of old migration command, etc. I would be giving a series of processes that one can follow to fix the migration issues
Drop the Database
The fastest solution which I don’t recommend but which is the easiest way, if you are starting out a project which does not have any record or no valuable record in the database is
- Delete all the files from the
migrations
folders from different apps. - Drop the SQL database schema.
- Run
python manage.py makemigration
- Run
python manage.py migrate
Voila! Your migration issue is solved, but this also would mean that you now need to add the data to your database.
Fake old migrations
If dropping your database is not an option then the next best solution is to find the last working state of the database and then create new migration files.
- Find the last good state where your database was working.
- Comment out all the new
models.py
file changes - Delete all the files from the
migrations
folder. - Truncate
django_migrations
table - Run
python manage.py makemigrations
- Run
python manage.py migrate --fake
- Uncomment the changes which you did in step 2.
- Run
python manage.py makemigrations
- Run
python manage.py migrate
Now your migration is complete and the database is in a working state. Use this step only for any side project or for applications where your code won’t go live to production or no other developers are working.
This is not recommended at all if you are working for production application, because for any production application you would need to commit the migration files and this process will break when the code reached your production or any other developer.
Reverse Migration
This is by far the best solution that I recommend or follow for solving any migration issue. Most Django developers only learn about performing forward migration, they don’t learn about reversing migration. Now we shall see how we can use the Django management command to perform reverse migration. Let us say we have books
app, which has 4 migration files, and while performing the third migration you are seeing some unwanted migrations errors. Let us see how you can solve this problem
- Lets us assume the error is happening after we performed some change in the database after
0002
the migration file. We know that the issue happened due to0003
or0004
migration step. - The first step would be to reverse both the migrations using Django migrate command.
python manage.py migrate books 0002
would simply reverse all the migrations which were performed after0002
step. - You can verify this by opening the
django_migrations
table. - Once your database is migrated to an old working state, you can now delete the
0003
and0004
files. - Run
python manage.py makemigrations
, this would create a new migration file that would contain all the changes of the models - Run
python manage.py migrate
, this would run the new migration files change to the database.
Now your migration issue is solved. This is by far the best solution I have come across whenever I find migration issues with Django. One of the challenges you might face, is to identify the migration file which is causing the issue the migrations step or the identify the last good migration step where you can revert back
Migrations | Django documentation | Django
Django
Ситуация: ты пытаешься выполнить миграции в Django. Но появляется ошибка «no changes detected» и ничего не происходит. Как исправить ошибку и провести миграцию?
Как правило, эта ошибка возникает после попытки «перекроить» базу данных. Например, ты решил, что имеющаяся база данных, ее структура требует изменений. Скажем, нужно убрать лишние поля. Быстрый и простой способ — полностью «перекомпоновать», пересоздать базу данных.
Для этого удаляется база данных и файлы миграции. Соответственно, это «костыльный» способ. Так как при этом удаляются все записи. На этапе разработки сайта или учебного проекта это возможно. На реальном сайте маловероятно — так как удаляется весь контент.
👉 При удалении файлов миграции можно допустить ошибку — удалить файл «__init__.py«. Дело в том, что для Django папка «migrations» воспринимается как приложение. И файл «__init__.py» является обязательным. Без него и возникает ошибка «no changes detected».
Проверяем, есть ли на месте этот файл. Если нет, то просто создаем его. Заметь — в названии используются двойные нижние подчеркивания. Сам файл оставляем пустым.
📢 Другие причины ошибки no changes detected
Твое приложение обязательно должно быть добавлено в INSTALLED_APPS файла «settings.py»:
Также проверяем наличие файла «__init__.py» в папке твоего приложения (где у тебя лежит файл «views.py» с представлениями, статические фалы и сама папка «migrations»).
В файле «models.py» классы должны наследоваться от «django.db.models.Model». В «models.py» должен быть соответствующий импорт, а в самом классе соответствующая запись в круглых скобках.
Проверяем, нет ли семантических ошибок в «models.py».
Также возможны ошибки при настройках Git. В частности в файле «.gitignore».