Миграцию ни одну не сделал и не могу запустить сервер, сделать makemigrations, migrate вылетает эта ошибка:
django.db.utils.ProgrammingError: ОШИБКА: отношение «authorization_university» не существует
LINE 1: …le», «authorization_university».»decryption» FROM «authoriza…
^
Код ORM:
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class University(models.Model):
university_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=50)
decryption = models.CharField(max_length=200)
class Group(models.Model):
group_id = models.AutoField(primary_key=True)
title = models.CharField(max_length=50)
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
middle_name = models.CharField(max_length=150, blank=True)
class Regkey(models.Model):
key = models.IntegerField()
class Profile_student(models.Model):
profile = models.OneToOneField(Profile, on_delete=models.CASCADE)
group = models.ForeignKey(Group, on_delete=models.CASCADE)
Обнаружил что когда удаляю функцию в forms.py, спокойно все делается и запускается сервера и миграция:
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Regkey, University, Group as groupdb
def func_university(): #ВОТ ЭТУ ФУНКЦИЮ
all_university = University.objects.all()
university_list = ()
university_array = []
for university_for in all_university:
university_list = (university_for.university_id, university_for.title)
university_array.append(university_list)
return university_array
class SignUpFormStudent(UserCreationForm):
first_name = forms.CharField(label='Имя')
second_name = forms.CharField(label='Фамилия')
middle_name = forms.CharField()
group = forms.CharField(label='Группа')
university = forms.ChoiceField(widget=forms.Select, choices=func_university())
email = forms.EmailField()
def clean(self):
reg_data = super(SignUpFormStudent, self).clean()
university = reg_data.get("university")
group = reg_data.get("group")
email = reg_data.get("email")
if not groupdb.objects.filter(group = group, university = university):
msg = 'Такой группы нет'
self._errors['group'] = self.error_class([msg])
del reg_data['group']
if User.objects.filter(email = email):
msg = 'Эта электронная почта занята'
self._errors['email'] = self.error_class([msg])
del reg_data['email']
return reg_data
class Meta:
model = User
fields = ('username', 'email', 'group', 'password1', 'password2')
class SignUpFormDean(UserCreationForm):
email = forms.EmailField()
first_name = forms.CharField(label='Имя')
second_name = forms.CharField(label='Фамилия')
middle_name = forms.CharField()
university = forms.ChoiceField(widget=forms.Select, choices=func_university())
regkey = forms.CharField(label='Номер ключа', max_length = 16)
def clean(self):
data = super(SignUpFormDean, self).clean()
regkey_input = data.get("regkey")
if not regkey.objects.get(key = regkey_input):
msg = 'Неверный ключ или он уже был использован'
self._errors['regkey'] = self.error_class([msg])
del data['regkey']
return data
class Meta:
model = User
fields = ('username','first_name','second_name', 'email', 'regkey', 'password1', 'password2')
Ситуация: ты пытаешься выполнить миграции в 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».
Поделиться в соц сетях
You ran makemigrations, then migrate and yet Django dares to throw an error? Incomparable betrayal! Let’s look through several cases.
Sidenote
For ages encountering migrations errors, I have been wipin the entire database and migrations files. Until one day an error occurred at a production server. There was no other option but to calm down and learn how to fix it.
🧸 Relation does not exist 1: not applied by you or Django
Run the command showmigrations and look at the output. If you see something like this:
firstapp
[X] 0001_initial
[X] 0002_auto_20190819_2019
[X] 0003_auto_20190827_2311
[ ] 0004_testunit
That means that the 0004 migrations was not applied, so just run migrate. If it stays misapplied or to avoid wasting time you can run this:
migrate firstapp 0004_testunit
If not, look further.
💔 Relation does not exist 2: You removed a migration’s file
Sidenote
The point of each migrations is to find the difference between the last version of the database structure and the current one. But Django does not look at the database itself, it compares your current models.py files with a virtual database made from migrations.py files. Then Django writes the changes down in new migrations files. And only with migrate you apply these changed to the database.
So if you remove something from migrations/ folder, the database will stay the same, but the Django’s idea of it won’t.
Case
So, you added a field type to a class Tag:
class Tag(models.Model)
name = models.CharField(max_length=100)
type = models.CharField(max_length=100)
You made a migrations, say, number 0002, it contains adding type field. Then you removed the migrations. After that, you made some changes, lived your best live, and decided to make migrations again.
Django will include creation of the type field to the migrations again. Therefore applying this migrations will give you an error:
ProgrammingError: column "tag_type" of relation "tag" already exists
How to Solve it 🧰
1. From migration file 0002_something.py remove the line about creating the type field.
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('firstapp', '0002_something'),
]
operations = [
...
# This .AddField below:
migrations.AddField(
model_name='tag',
name='type',
field=models.Charfield(max_length),
),
...
]
2. Migrate the 0002_something.py file:
migrate firstapp 0002_something
3. Make a new migration (it must only contain creating the type field):
makemigrations
4. Fake apply it like this:
migrate firstapp 0003_something_two --fake
🔨 Relation does not exist 2: Renaming a field was not applied
This mysterious thing happened. I renamed type to type_name and I have a migrations that states it:
...
operations = [
migrations.RenameField(
model_name='tag',
old_name='type',
new_name='type_name',
),
]
...
And yet I get this error:
ProgrammingError at /test relation "firstapp_tag_type_name" does not exist

Possible culprit (myself and mass replace) a.k.a Sloppy Development installment
While changing names in the whole project automatically, I also unwillingly changed them in the migrations files. It is a great temptation to remove it all at once, but be careful. That may be the problem.
How to Solve it 🧰
Attempt #1: Order is wrong
The type field may have been altered before it was created because of the mass replace.
Try finding the whole life cycle of type field in your migrations – where it was added, where it was altered etc.
Attempt #2: Remove Migration file concerning the field
Remove every mention of the type field in migrations’ files (in operation). Then do whatever you want (rename it etc.) and make a migration again.
If the change is the only one in a migrations file, remove it all together.
You can remove the whole migration file, if it only contains type field manipulations. But be careful and alter dependencies for the following migration file (replace the deleted file’s name with the one before it).
Say, migrations’s files are 0002_something_before.py, 0003_something.py (removed) and 0004_brave_new.py.
So, after deleting 0003_something.py, in 0004_brave_new.py file:
dependencies = [
('firstapp', '0003_something'),
]
Replace 0003_something.py with0002_something_before:
dependencies = [
('firstapp', '0002_something_before'),
]
Otherwise you will get an error like this:
django.db.migrations.exceptions.NodeNotFoundError: Migration firstapp.0003_something_something dependencies reference nonexistent parent node
Then, makemigrations and migrate.
Attempt #3: Remove every mention of the problematic field
If simply removing a migration and making another one doesn’t help…
Embrace yourself and remove every mention of type field. For my personal project, that inspired this post, it was quite time consuming.
However, as I see it now, you can’t just remove the field and make migrations of that, because type does not exist in the database. However, I can’t answer why.
You need to remove it from everywhere.
Then, makemigrations must show nothing, and the error won’t make am appearance.
🚫 Why you shouldn’t remove migrations
Summing up, Django does not care about database itself, except for when it returns errors. So Django’s idea of the database is made of migrations it have. That’s why when you run makemigrations, you get errors about migration files.
After applying new migrations, you will start getting all sorts of surprises: InvalidCursorName cursor does not exist or good old ProgrammingError: column does not exist and ProgrammingError: column of relation already exists.
Take my advice – don’t remove migrations because of migration errors, better learn how to work with them. Because in production you won’t be able to flush the database without a trouble (you kind of can, but you will need to insert missing data afterwards).
But if you did remove migrations…
Oh, been there.
I can say one thing – you will need to keep reversing changes to the database until you don’t get any more errors. And then make this changes again the same way I showed you here. And while in most cases Attempt #3 works, some day it may fail you.
One day I will emulate this and come back and update this post with a quick solution, but now I am triggered enough by just the mention of it.
Transforming one field to another
You can transform pretty much everything with an exception.
Adding a through table to M2M relation (or backwards)
Usually you want to add a through table to store additional data about the relation, not remove it. Either way, Django won’t allow this transition.
Say, Django can remove all the additional data, but constraints like unique_together can ruin your architecture. So you need to do it manually.
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,6114 gold badges39 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
7076 silver badges11 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
7491 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,0931 gold badge21 silver badges37 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,0102 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
3311 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
3774 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_migrationsin 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_migrationstable:delete from django_migrations;with a commandDELETE FROM django_migrations WHERE app='my_app'; - For every app, delete its
migrationsfolder: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
6536 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.7k9 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
4666 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
9,6116 gold badges44 silver badges78 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
5733 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,6711 gold badge16 silver badges20 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
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,6114 gold badges39 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
7076 silver badges11 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
7491 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,0931 gold badge21 silver badges37 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,0102 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
3311 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
3774 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_migrationsin 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_migrationstable:delete from django_migrations;with a commandDELETE FROM django_migrations WHERE app='my_app'; - For every app, delete its
migrationsfolder: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
6536 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.7k9 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
4666 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
9,6116 gold badges44 silver badges78 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
5733 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,6711 gold badge16 silver badges20 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