Django unique, null and blank CharField giving 'already exists' error on Admin page

前端 未结 7 2080
旧巷少年郎
旧巷少年郎 2021-01-01 13:30

I\'ve been getting the most weird error ever. I have a Person model

class Person(models.Model):
    user = models.OneToOneField(User, primary_key=True)
    f         


        
7条回答
  •  失恋的感觉
    2021-01-01 13:58

    None of the answers clearly describe the root of the problem.

    Normally in the db you can make a field null=True, unique=True and it will work... because NULL != NULL. So each blank value is still considered unique.

    But unfortunately for CharFields Django will save an empty string "" (because when you submit a form everything comes into Django as strings, and you may have really wanted to save an empty string "" - Django doesn't know if it should convert to None)

    This basically means you shouldn't use CharField(unique=True, null=True, blank=True) in Django. As others have noted you probably have to give up the db-level unique constraint and do your own unique checks in the model.

    For further reference, see here: https://code.djangoproject.com/ticket/4136
    (unfortunately no good solution decided at time of writing)

提交回复
热议问题