Django自定义User模型:可为空字段唯一约束失效问题排查
问题解决:Django自定义User模型中空字段的唯一约束冲突
问题根源
你在字段上设置的unique=True会让Django自动生成无条件的数据库唯一约束,而数据库的唯一约束会把NULL视为一个唯一值——也就是说,当你创建第二个mobile_number为NULL的用户时,数据库会认为这两个NULL重复,触发IntegrityError。
虽然你在Meta类里添加了带condition的UniqueConstraint,但这个条件约束和字段unique=True生成的无约束唯一索引是共存的,后者才是导致冲突的核心原因。
解决方案
直接去掉字段定义中的unique=True参数,只保留Meta类里的带条件UniqueConstraint即可。
修改后的核心代码片段
# 修改passport字段 passport = models.CharField( max_length=255, # 移除unique=True null=True, blank=True, error_messages={ "unique": _("A user with this passport number already exists."), }, ) # 修改identification字段 identification = models.CharField( validators=[id_regex], max_length=15, # 移除unique=True blank=True, null=True, error_messages={ "unique": _("A user with this identification number already exists."), }, ) # 修改mobile_number字段 mobile_number = models.CharField( validators=[mobile_num_regex], # 移除unique=True max_length=11, null=True, blank=True, error_messages={ "unique": _("A user with this mobile number already exists."), }, )
后续操作
- 生成迁移文件:
python manage.py makemigrations
- 执行迁移:
python manage.py migrate
效果验证
- 可正常创建多个
mobile_number/passport/identification为空的用户,不会触发唯一约束错误 - 当这些字段填入非空值时,重复值会触发唯一约束报错,完全符合需求
内容的提问来源于stack exchange,提问作者Khaleel
相关产品推荐
相关产品推荐

