Django unique, null and blank CharField giving 

2020-06-07 07:26发布

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)
    facebook_id = models.CharField(max_length=225, unique=True, null=True, blank=True)
    twitter_id = models.CharField(max_length=225, unique=True, null=True, blank=True)
    suggested_person = models.BooleanField(default=False)

I recently added the twitter_id field. When I access the Django admin page, and try to change the 'person' into a suggested_person, I get the following error:

 Person with this Twitter id already exists.

I find this error to be extremely strange because the Facebook_id field is designed the exact same way as the Twitter_id field.

What could be the reason for this?

7条回答
兄弟一词,经得起流年.
2楼-- · 2020-06-07 07:55

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

查看更多
登录 后发表回答