72
This happens when a different field was marked as primary key with primary_key=True
earlier and you are removing that (in case of which django tries to add an id
primary key).
That Django is asking for a default value for a primary key seems to be a bug.
To work around this problem, follow these steps:
-
Supply a random default value when prompted during makemigrations.
-
Go to the migration file generated (under
your_app\migrations\
and delete thedefault=x,
, x being the random value you supplied in step 1. -
While you are at the migration file, make sure the order of actions make sense (e.g., remove/alter one primary key before adding another). Save and close.
-
Migrate as usual.
26
you could set `default=”” and also editable=False.
E.g first_name = models.CharField(max_length=50, default="", editable=False)
.
Adding id field is unnecessary. Django will add it automatically.
Edit: Deleting the last migration files in your migrations folder and retry again. If it doesn’t work, repeat the same process, you will know you have deleted the right file when your “makemigrations” command works.
- [Django]-What are the options for overriding Django's cascading delete behaviour?
- [Django]-Django max_length for IntegerField
- [Django]-Serializer call is showing an TypeError: Object of type 'ListSerializer' is not JSON serializable?
3
You need to set a default value. For example:
field_eg = models.CharField(default="")
means:
name = models.CharField(max_length=100, default="")
- [Django]-Django CMS fails to synch db or migrate
- [Django]-The STATICFILES_DIRS setting should not contain the STATIC_ROOT setting
- [Django]-Atomic increment of a counter in django
3
Check Your Migration Files
./manage.py showmigrations <App Name>
[X] 0001_initial
[X] 0002_auto_20181204_1110
Revert Your Migrations Using
./manage.py migrate <App Name> <migration file name>
Eg: 0001_initial
.
Or use zero (for complete migration revert)
./manage.py migrate <App Name> zero
Check Your Migrations
./manage.py showmigrations <App Name>
[ ] 0001_initial
[ ] 0002_auto_20181204_1110
Now delete all revert migrations and migrate again.
./manage.py migrate <App Name>
- [Django]-How do I use a dictionary to update fields in Django models?
- [Django]-Django "Cannot add or update a child row: a foreign key constraint fails"
- [Django]-Django Setup Default Logging
1
I ran into similar problem when doing makemigration. I had primary key with name ‘Identity’ and other fields in my models to which I applied makemigrations. Later, I changed primary key name to ‘_id’ and I got this error.
You are trying to add a non-nullable field ‘_id’ to swapidentity without a default; we can’t do that (the database needs something to populate existing rows).
Error is bit misleading, but if you change back ‘_id’ to ‘Identity’ you will not get that error.
How to fix?
Delete migration script generated under migrations package. Or manually change primary key in your generated migration script.
- [Django]-Django Rest-Framework nested serializer order
- [Django]-Get the list of checkbox post in django views
- [Django]-Running fabric script locally
1
In my opinion, completely deleting the migrations is a lazy and bad idea. I did a snafu similar to @Afiz Momin and was able to dig myself out.
I had the following setup:
- A base abstract model.
- Override the
id
field after creation (bad idea) - All other subclasses triggered Django migrations to try to create the ID field from the parent class.
So I would get the following every single time I ran makemigrations
:
You are trying to add a non-nullable field 'id' to <tablename> without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows with a null value for this column)
2) Quit, and let me add a default in models.py
But there was a way out.
In my first attempt I would just seed a fake value in and then delete the created id
column, but this was obviously unsustainable. But on a whim I did the following:
- Backup the migrations directory to
migrations.orig
. - Run
./manage.py makemigrations
to make all migrations. - Inspect the newly-created migrations file
0001-initial
.
Chances are the model it’s complaining about (<tablename>
) is missing vital info. For me, it was missing the bases
argument:
migrations.CreateModel(
name='<ModelName>',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('some_field', models.IntegerField()),
# ... other fields ...
],
options={
'abstract': False,
},
bases=(<base_classes>),
),
- Now go back to
migrations.orig
and search for the the migration where the model is first created. The migration line will look similar to the one above. - Once you find the line in
migrations.orig
, modify it to match the new migration code. - Restore your original migrations. Delete
migrations
and renamemigrations.orig
tomigrations
. - Just for good measure, run
./manage.py makemigrations
and./manage.py migrate
. You should get no error messages anymore! - If it complains about another model, follow the same procedure described.
- [Django]-Django: Populate user ID when saving a model
- [Django]-Dynamically adding a form to a Django formset
- [Django]-How can I modify Procfile to run Gunicorn process in a non-standard folder on Heroku?
1
you happen to be generating a relationship between tables, what you have to do is add a field null = True
, in one of the fields of the tables that the error message is referring to (class contact_info).
- [Django]-The view didn't return an HttpResponse object. It returned None instead
- [Django]-Django SMTPAuthenticationError
- [Django]-How to access Django's field.choices?
0
This is happening because you have non-empty database. There must be line which has not been created through Django ORM.
Do the following:
python manage.py shell
from <path_to_your_models> import *
print len(list(contact_info.objects.filter(id = None)))
This way you find out how many such rows are there. If you want to keep them just make migration script with some value that you give it to it.
- [Django]-How do I perform a batch insert in Django?
- [Django]-Can Django automatically create a related one-to-one model?
- [Django]-Simple Log to File example for django 1.3+
0
This can also happen if you made some changes in your models.py and tried migrating afterwards. Happened to me once. Deleting the entire database didn’t help after all. In case the error is arriving after adding a Foreign Key, you cannot provide a default or it might be unsafe to set default as null.
Probably Django still has some of the previous migrations files in your myapp/migrations/ folder. Deleting those files might help.
- [Django]-Gunicorn + nginx: Server via socket or proxy?
- [Django]-Do I need Nginx with Gunicorn if I am not serving any static content?
- [Django]-How can I modify Procfile to run Gunicorn process in a non-standard folder on Heroku?
0
The database needs something to populate existing rows.
So here you want to define some value for it you can use default=””
contact_info = models.CharField(default="" ,max_length=15)
- [Django]-Unittest Django: Mock external API, what is proper way?
- [Django]-Django: How to get language code in template?
- [Django]-When to use get, get_queryset, get_context_data in Django?