目标

  • 需要把原来的必填字段改为非必填

    实现

  • 先在models里面更新了字段, 加上null=True, default=None, blank=True
1
2
name = CharField(max_length=64, verbose_name='姓名', null=True, default=None, blank=True)
account = CharField(max_length=64, verbose_name='账号', null=True, default=None, blank=True)
  • serializers更新
1
2
name = CharField(required=False)
account = CharField(required=False)
  • 执行python manage.py makemigrations
  • 执行python manage.py migrate

问题

  • 出现这种情况
1
This field may not be null.
  • 或者
1
This field cannot be blank.

解决

  • 需要把serializers改成这样
1
2
name = CharField(required=False, allow_blank=True, allow_null=True)
account = CharField(required=False, allow_blank=True, allow_null=True)

allow_blank=True 解决 This field cannot be blank.
allow_null=True 解决 This field may not be null.