I created a model with an email address as a user 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 return to the automatically generated id field as the primary key.
How to do it? I tried it differently, but everything failed. I am using Django 1.10.4 with Python 3.4.3 with a SQLite database.
- I just replaced the primary_key = True parameter with unique = True.
python manage.py makemigrations
complains:
You are trying to add an invalid id field to a user with no default value; we cannot do this (the database needs to fill in the existing lines).
If I specify 0
as the default, python manage.py migrate
will fail with django.db.utils.IntegrityError: UNIQUE constraint failed: login_user.id
Based on this message Change the primary key field to a unique field I tried to add Autofield manually, as in:
id = models.AutoField ()
Now python manage.py makemigrations
crash:
login.User.id: (fields.E100) AutoFields must set primary_key=True.
If I do as suggested by the error message, I get the same problem as in the first attempt: there is no default value.
- I tried to create the id = IntegerField (unique = True) field (after the Django documentation at https://docs.djangoproject.com/en/1.10/howto/writing-migrations/#migrations-that-add-unique-fields ), and then change the field type in 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, but migrate
fails with the trace and this error: django.db.utils.OperationalError: duplicate column name: id
It seems that you are trying to make an additional column "id", you donβt know why.
What is the right way to do this? Also, if this succeeds, will the ForeignKey fields that refer to my user be changed correctly?
source share