21
Django migrations are recorded in your database under the ‘django_migrations’ table. This is how Django knows which migrations have been applied and which still need to be applied.
Have a look at django_migrations table in your DB. It may be that something went wrong when your migration was applied. So, delete the row in the table which has the migration file name that is related to that column that ‘does not exist’. Then, try to re-run a migration.
42
I got the same problem (column not exist) but when I try to run migrate
not with makemigrations
(it is the same issue I believe)
-
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='yourapp';
-
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.
- [Django]-Allowing RabbitMQ-Server Connections
- [Django]-In Django, how do I check if a user is in a certain group?
- [Django]-Django database query: How to get object by id?
13
Here’s what i tried and it worked:
- Go and add manually the column to your table
- run python manage.py makemigrations
- go back drop that column you added
- run python manage.py migrate
- [Django]-Split models.py into several files
- [Django]-How do I package a python application to make it pip-installable?
- [Django]-Django: signal when user logs in?
11
I had a similar issue – the error message appeared when I clicked on the model on the django-admin site. I solved it by commenting out the field in models.py, then running migrations. Following this I uncommented the field and re ran the migrations. After that the error message disappeared.
- [Django]-How to monkey patch Django?
- [Django]-Switching to PostgreSQL fails loading datadump
- [Django]-Fighting client-side caching in Django
5
My case might be a bit obscure, but if it helps someone, it is worth documenting here.
I was calling a function in one of my migrations, which imported a Model of said migration regularly, i.e.
from myApp.models import ModelX
The only way models should be imported in migrations would be using e.g. RunPython:
def myFunc(apps, schema_editor):
MyModel = apps.get_model('myApp 'MyModel')
and then calling that function like so:
class Migration(migrations.Migration):
operations = [
migrations.RunPython(initialize_mhs, reverse_code=migrations.RunPython.noop),
]
Additionally the original import worked until I modified the model in a later migration, making this error harder to locate.
- [Django]-Django model blank=False does not work?
- [Django]-How to get an array in Django posted via Ajax
- [Django]-Django add extra field to a ModelForm generated from a Model
2
Just remove corresponding row migrations for that model in ‘django_migrations’ model in database.
And re run python manage.py migrate app_name
- [Django]-Django: Calculate the Sum of the column values through query
- [Django]-Modulus % in Django template
- [Django]-How to test auto_now_add in django
1
So, I always run into this sort of problem, so today I decided to try and work it out at the database level. Thing is, I changed a model field name which Django
didn’t bother reflecting in a migration file. I only found out later when I ran into problems. I later looked at the migration files and discovered there was no migration for that change. But I didn’t notice because I made other changes as well, so once I saw a migration file I was happy.
My advice. Create migration for each change one at a time. That way you get to see if it happened or not.
So here’s my working through it in MySQL.
open mysql console.
show databases; # see all my dbs. I deleted a few
drop database <db-name>; # if needed
use <db-name>; # the database name for your django project
show tables; # see all tables in the database
DESCRIBE <table-name>; # shows columns in the database
SHOW COLUMNS FROM <db-name>; # same thing as above
ALTER TABLE <table-name> CHANGE <old-column-name> <new-column-name> <col-type>; # now I manually updated my column name
If you’re using postgresql, just google the corresponding commands.
- [Django]-Django FileField upload is not working for me
- [Django]-Consolidating multiple post_save signals with one receiver
- [Django]-How to keep all my django applications in specific folder
1
The issue was in the Models for me, for some reason Django was adding ‘_id’ to the end of my Foreign Key column. I had to explicitly set the related named to the Foreign Key. Here ‘Cards’ is the parent table and ‘Prices’ is the child table.
class Cards(models.Model):
unique_id = models.CharField(primary_key=True, max_length=45)
name = models.CharField(max_length=225)
class Prices(models.Model):
unique_id = models.ForeignKey(Cards, models.DO_NOTHING)
Works after changing to:
class Cards(models.Model):
unique_id = models.CharField(primary_key=True, max_length=45)
name = models.CharField(max_length=225)
class Prices(models.Model):
unique_id = models.ForeignKey(Cards, models.DO_NOTHING, db_column='unique_id')
- [Django]-How to TRUNCATE TABLE using Django's ORM?
- [Django]-Django release 1.5: 'url' requires a non-empty first argument. The syntax changed in Django 1.5
- [Django]-How to create password input field in django
1
When I get this error, my extreme way to solve it is to reset my database:
- Reset your database
For Postgresql on Heroku:
Heroku > your_app > Resources > database > add-ons > click on your database and open it
For postgresql
settings > Reset database
- Delete all files in your_app > migrations >
__pycache__
except__init.py__
- Delete all files in your_app > migrations except
__pycache__
folder and__init.py__
-
Then run:
python manage.py makemigrations
python manage.py migrate
python manage.py createsuperuser
type in to create your superuser, then run:
python manage.py makemigrations
python manage.py migrate
python manage.py
If you are able to inspect your models from your admin section, then it should be all okay now.
- [Django]-How to manually assign imagefield in Django
- [Django]-Test that user was logged in successfully
- [Django]-Difference between auto_now and auto_now_add
0
I tried all these answers with not much luck! What I did to have this problem solved with no harm was to go back through the migration files and find where the actual model was being created for the first time then manually add the field (in the column not being existed error message). Until if you run makemigrations --dry-run
you get/see "No changes detected" and that worked. Basically, in my case, I had to carefully take my desired db changes back in time in proper migration file, rather creating a new migration now at the end of migration dependency chain.
- [Django]-Celery : Execute task after a specific time gap
- [Django]-No module named pkg_resources
- [Django]-Dropdown in Django Model
0
- Open the latest py file created after running the makemigrations command inside migrations folder of that particular app.
- Inside class Migration there is a list attribute called ‘operations’.
- Remove the particular elements migrations.RemoveField(…).
- Save and run
python manage.py migrate
.
- [Django]-Why is logged_out.html not overriding in django registration?
- [Django]-Django models: get list of id
- [Django]-<Django object > is not JSON serializable
0
A easier solution to the problem is to make your models exactly like it is in the migration first. and run python manage.py migrate.
Then revert those changes
Run
python manage.py makemigrations
python manage.py migrate
To check for which migrations are applied and which are not, use -:
python manage.py showmigrations
- [Django]-How do I install psycopg2 for Python 3.x?
- [Django]-How can i test for an empty queryset in Django?
- [Django]-Django – How to make a variable available to all templates?
0
I solved a similar problem by deleting all migrations files (Don’t forget to make a backup) and python manage.py makemigrations
all of them into one clean file in development and pulling new files on the server. Before then I had dropped existing tables on the PostgreSQL.
- [Django]-Django – getting Error "Reverse for 'detail' with no arguments not found. 1 pattern(s) tried:" when using {% url "music:fav" %}
- [Django]-How to get GET request values in Django?
- [Django]-Django unique_together with nullable ForeignKey
0
I was getting this error for some reason when Django was looking for a column of type ForeignKey
named category_id
when the actual name in the database was category
. I tried every Django solution I could imagine (renaming field, explicitly setting column name, etc.). I didn’t want to drop tables or rows as this was a production database. The solution was simply to rename the column manually using SQL. In my case:
ALTER TABLE table_name
RENAME COLUMN category TO category_id;
Make sure you backup your database, ensure this won’t break any other applications consuming that particular table, and consider having a fallback column if necessary.
- [Django]-Is not JSON serializable
- [Django]-Django class-based views with inline model-form or formset
- [Django]-Django: Get list of model fields?
0
For me, this was being caused because someone had accessed the model globally in a module. The module was attempting to retrieve an instance of the model every time it was loaded. Makemigrations loads the app, so this was attempting to query a model that had new fields before the migration was created or applied. You can see if this is happening for you by checking the stack trace…
- [Django]-How do I POST with jQuery/Ajax in Django?
- [Django]-Django no such table:
- [Django]-Django 1.4 – can't compare offset-naive and offset-aware datetimes
-1
These are the potential reasons why you encounter that problem:
Check Migrations
- Make sure that you’ve applied the migrations with your application name at the end
python manage.py makemigrations app-name
Validate Database Schema
- Confirm that the database schema aligns with the model definitions within your Django application. Utilize a suitable database tool or query to examine the actual schema.
Retry Migration
- In case there is suspicion of an issue with a specific migration, attempt to roll back to a previous migration and then reapplied migrations.
python manage.py migrate app_name zero # Rollback all migrations
python manage.py migrate # Apply migrations again
Correct Definitions
- Double-check for any typos in your model definitions, particularly in field names. Maintain consistency between your model and database naming conventions.
Verify Database Connection:
- Validate that your Django application has established connectivity with the correct database and that relevant settings in your settings.py file are accurate.
Resetting the Entire Database (last resort):
- If all else fails and data loss can be tolerated, it may be necessary to completely reset the database before reapplying migrations
python manage.py flush
- [Django]-How to manage local vs production settings in Django?
- [Django]-Custom Filter in Django Admin on Django 1.3 or below
- [Django]-Django optional URL parameters
- [Django]-Django – comparing old and new field value before saving
- [Django]-"Too many values to unpack" Exception
- [Django]-Django comparing model instances for equality