I have created a model with email address as custom primary key as follows:
email = models.EmailField(max_length=255, primary_key=True,)
Now I realized that this is not a good idea in my case and I would like to go back to the automatically generated id field as primary key.
How to do this? I tried this in different ways but all failed. I am using Django 1.10.4 with Python 3.4.3 with an SQLite database.
- I just replaced the primary_key=True option by unique=True.
python manage.py makemigrations
complains:
You are trying to add a non-nullable field 'id' to user without a default; we can't do that (the database needs something to populate existing rows).
If I specify 0
as default value, python manage.py migrate
fails with django.db.utils.IntegrityError: UNIQUE constraint failed: login_user.id
Based on this post Change Primary Key field to unique field I tried to add an Autofield manually, as in:
id = models.AutoField()
Now python manage.py makemigrations
fails with:
login.User.id: (fields.E100) AutoFields must set primary_key=True.
If I do as suggested by the error message, I get the same issue as in my first try: missing default value.
- I tried to make a field id=IntegerField(unique=True) (following Django documentation at https://docs.djangoproject.com/en/1.10/howto/writing-migrations/#migrations-that-add-unique-fields) and then change the field type to AutoField(primary_key=True). At the same time, I need to change the email field to unique=True to avoid having two primary keys. After these changes,
makemigrations
works fine butmigrate
fails with a traceback and this error:django.db.utils.OperationalError: duplicate column name: id
It seems to be trying to make an additional 'id' column, don't know why.
What is the correct way to do this? Also, if it succeeds, will ForeignKey fields that refer to my User be updated correctly?