Home > Software design >  How to save model in Django with unique but null fields
How to save model in Django with unique but null fields

Time:11-10

How can I save a model that should be unique but also allowed to be null in Django. For instance I have the following model...

class PetOwner(models.Model):
    """Model representing a pet owner."""

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    first_name = models.CharField(max_length=50, help_text="Enter owner's first name")
    last_name = models.CharField(max_length=50, help_text="Enter owner's last name")
    email = models.EmailField(
        max_length=50, blank=True, unique=True, help_text="Enter owner's email"
    )
    phone_number = models.CharField(
        max_length=15, blank=True, unique=True, help_text="Enter owner's phone number"
    )
    address = models.ForeignKey(
        "Address", on_delete=models.SET_NULL, null=True, blank=True
    )

I want my app to work the following way. A PetOwner can sign up but when they do they initially only sign up with a username, password, a confirmation password, and first_name, and last_name. I want my to have a profile page which will allow for updating the PetOwner to include their phone_number but I do not necessarily want to make this a requirement. I decided that I'd make phone_number field null=True and blank=True but as soon as I register a second user I get a django.db.utils.IntegrityError: UNIQUE constraint failed: app_petowner.phone_number error. I believe it is because when I register a user for some reason instead of phone_number being None even when I did not actually add a phone number at all it shows up as an empty string. Not sure why this is happening and I am not sure how to fix it.

CodePudding user response:

I think that the problem is that you actually sending empty string, not null. You have to explicitly set phone number to None, before saving. Actually you can check if it is truth. Just make if phone_number == "": print something

  • Related