Reputation: 1579
I have changed django.contrib.auth.user model where I have made the email id to be unique. After which I added a datamigration to reflect the same-
python manage.py datamigration appname unique_password. Followed by python manage.py schemamigration appname --auto-->no changes. Finally, python manage.py migrate appname.
Migrating forwards to 0003_unique_password
Now when I add a user whose email is not unique, it gives me an error and does not let me create the user through the django admin. But when i do: >
python manage.py shell
from django.contrib.auth.models import User
How can I add an unique constraint to django.contrib.auth.user.email for an existing project (with data)?
Upvotes: 4
Views: 1329
Reputation: 15766
Checks for uniqueness occur during model validation as per the Model validation documentation. Calling save()
on the model doesn't automatically cause model validation. The admin application will be calling model validation.
Nothing prevents you from creating a User
object in Python such as user=User('cust1','123','[email protected]')
and then doing a user.save()
. If there are uniqueness checks at the database level, you'll likely get an exception at this point. If you want to check before doing the save, call is_valid()
on the Model instance.
If you want every User
object to be automatically validated before save, use the pre_save Django signal to do Model validation before the save proceeds.
Upvotes: 1