Mysql Django CharField作为主键仍然允许保存空值
目前我有以下模型,我想将CharField设置为主键(我的数据库是Mysql) 它在报告中说: primary_key=True表示null=False,unique=True。只有一个小学 对象上允许使用密钥 在Mysql中,主键具有以下结构: 客户id,类型=varchar(255),排序规则=latin1\u swedish\u ci, 属性=空白空值=否,默认值=无,注释=空白,额外值=空白 但是当我尝试使用主键为null值的save()方法时:Mysql Django CharField作为主键仍然允许保存空值,mysql,django,django-models,Mysql,Django,Django Models,目前我有以下模型,我想将CharField设置为主键(我的数据库是Mysql) 它在报告中说: primary_key=True表示null=False,unique=True。只有一个小学 对象上允许使用密钥 在Mysql中,主键具有以下结构: 客户id,类型=varchar(255),排序规则=latin1\u swedish\u ci, 属性=空白空值=否,默认值=无,注释=空白,额外值=空白 但是当我尝试使用主键为null值的save()方法时: Customer.objects.cre
Customer.objects.create(customer_id=None, name="abc")
它仍然在主键中保存空值而不返回任何错误或验证,这是为什么
编辑:
在Mysql中保存后,将显示customer_id=blank的值(当尝试将其保存为None时)。为什么在保存customer\u id=None时将其设置为空
When you create object for the first time
Customer.objects.create(customer_id=None, name="abc")
It will store customer_id value as '' (empty value, not null) and there are no other object we have created till now, so it's unique too.
Now when you again create an Customer object
Customer.objects.create(customer_id=None, name="xyz")
This will throw an error 'django.db.utils.IntegrityError: UNIQUE constraint failed: customers.customer_id' because we already have empty value in our customer_id value. So, this is throwing an error of UNIQUE constraint
When you create object for the first time
Customer.objects.create(customer_id=None, name="abc")
It will store customer_id value as '' (empty value, not null) and there are no other object we have created till now, so it's unique too.
Now when you again create an Customer object
Customer.objects.create(customer_id=None, name="xyz")
This will throw an error 'django.db.utils.IntegrityError: UNIQUE constraint failed: customers.customer_id' because we already have empty value in our customer_id value. So, this is throwing an error of UNIQUE constraint