-
Notifications
You must be signed in to change notification settings - Fork 13
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[Migrations] null=True, unique=True
Raises django.db.utils.IntegrityError: UNIQUE constraint failed
when running migration
#14
Comments
Happening with a SQLite database. When unique=False and the migration succeeds, all of the values for the column are an empty string instead of |
Can you confirm whether this issue also affects a |
Yes, I can confirm that this same issue does not occur with a regular CharField (Django 3.1). The issue seems to be in the current implementation of class PhoneField(phone_models.PhoneField):
def get_prep_value(self, value):
if not value:
# return ''
return None
if not isinstance(value, PhoneNumber):
value = PhoneNumber(value)
return value.cleaned I can submit a PR if you like. |
@va-andrew any interest in this? I will close the issue if not. |
Hey, thanks for the notice! Overall, I wasn't expecting use of The only concern I have is to make sure we're not upsetting the behavior of existing use cases. Is there a way we can make |
I don't know if I agree that it's an anti-pattern. In my typical usage of Really what I want a specialty field (as with URLField, and EmailField) to do is if any value (and I consider the empty string to be a value) is going to be saved into a Regardless, this is how you would "return None only if null=True is set on the field": class PhoneField(phone_models.PhoneField):
def get_prep_value(self, value):
if not value:
return None if self.null else ''
if not isinstance(value, PhoneNumber):
value = PhoneNumber(value)
return value.cleaned |
Just thought I'd add a me too. I think being able to prevent users entering the same phone number for different companies is a valid user case. unique=True is useful and only works with empy fields if they are null=True |
@jjorissen52 Your code snippet fixed the issue for me, thanks. |
To reproduce, make sure some rows already exist for MyModel, then add a
PhoneField
to it.python manage.py makemigrations python manage.py migrate # django.db.utils.IntegrityError: UNIQUE constraint failed: new__myapp_mymodel.phone
The text was updated successfully, but these errors were encountered: