0

I have a Django app using a PostgreSQL db, where the user migration has an email field with unique=True. My User model has:

email = models.EmailField(_('email address'), unique=True, blank=True)

I want to be able to create multiple users with blank emails, but when the email is not blank it has to be unique. Currently, when I create two users with a blank email I get this error:

duplicate key value violates unique constraint "accounts_user_email_b2644a56_uniq"

EDIT: I have added this to the save method in the User model:

if not self.email:
    self.email = None
GluePear
  • 7,244
  • 20
  • 67
  • 120
  • Possible duplicate of [Unique fields that allow nulls in Django](https://stackoverflow.com/questions/454436/unique-fields-that-allow-nulls-in-django) – Arghya Saha Nov 30 '18 at 12:38

1 Answers1

4

A unique constraint will allow multiple rows with value null, but it won't allow multiple rows with value empty string.

Therefore, you should set null=True on the field, and then set email=None instead of email="".

Alasdair
  • 298,606
  • 55
  • 578
  • 516