django rest manytomany create
多对多创建数据时,想要创建一条被关联的数据为空的新数据,结果报错,报错如下
modles.py
class AuthorityEntry(models.Model):
"""
"""
platform_services = models.CharField(max_length=64, verbose_name='平台/服务')
level = models.IntegerField(choices=((1, 'BU'), (2, 'project')),default=1,verbose_name='级别')
detail = models.CharField(max_length=128, verbose_name='权限详情')
cn_detail = models.CharField(max_length=128, verbose_name='权限中文详情',null=True)
type = models.IntegerField(choices=((1, 'ReadWrite'), (2, 'ListOnly'), (3, 'ReadOnly')),default=1,verbose_name='读写类型')
remark = models.CharField(max_length=512, null=True,blank=True)
class Meta:
verbose_name_plural = '权限条目'
class Authority(models.Model):
"""
权限条目:多对多关联权限条目表
"""
project = models.TextField(verbose_name=' ',null=True)
is_all_entries = models.BooleanField(default=False,verbose_name="是否选择全部权限条目")
authority_entries = models.ManyToManyField(to='AuthorityEntry',verbose_name='关联权限条目',null=True)
remark = models.CharField(max_length=512, null=True,blank=True)
class Meta:
verbose_name_plural = '权限项'
想要创建一个权限项 并且多对多管理的权限条目为空 走创建post请求
这是上传的data
postdata:
{ "effect":"1",
"platform_services":"iam",
"region":"*",
"project":"*",
"level":1,
"is_all_entries":false,
"authority_entries":[],
"remark":"authority_entries 为空 "
}
结果报错
序列化类:
class AuthorityEntrySerializer(ModelSerializer):
class Meta:
model = AuthorityEntry
fields = '__all__'
class CreateUpdateAuthoritySerializer(ModelSerializer):
class Meta:
model = Authority
fields = '__all__'
修改
class CreateUpdateAuthoritySerializer(ModelSerializer):
authority_entries=AuthorityEntrySerializer(many=True,read_only=True)
class Meta:
model = Authority
fields = '__all__'
加上这句话,就可以了