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

前端 未结 7 2043
旧巷少年郎
旧巷少年郎 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 14:21

    The root of the problem is that Django persist the empty value as empty-string, and not as null. To fix this, you can subclass CharField as follows:

    class CharNullField(models.CharField):
        description = "CharField that stores NULL"
    
        def get_db_prep_value(self, value, connection=None, prepared=False):
            value = super(CharNullField, self).get_db_prep_value(value, connection, prepared)
            if value=="":
                return None
            else:
                return value
    

    So get_db_prep_value will make it sure that null gets persisted

    0 讨论(0)
提交回复
热议问题