class TagGroupCreateUpdateSerializer(CustomModelSerializer):
tags = serializers.ListSerializer(child=serializers.CharField(max_length=50), help_text="标签", write_only=True)
class Meta:
model = TagGroup
fields = ["name", 'tags']
def create(self, validated_data):
tags = validated_data['tags']
del validated_data['tags']
tg = super().create(validated_data)
for tag in tags:
Tag.objects.create(group=tg, name=tag)
# 企业微信添加标签组和标签(注意:企业微信不支持创建空标签组。所以如果没有tags就不创建标签组)
client = get_wechat_client(4)
tg.wechat_add_tag(client)
return tg
在添加和修改时可用这种方式,也就是前端传过来一个tagGroup中的name字段同时传过来多个tags字段,
用这种方式就是序列化多个tags字段,它可以理解为一个声明。具体的添加操作是在create中完成的。
serializers.ListSerializer(child=serializers.CharField(max_length=50), help_text=“标签”, write_only=True)
该代码示例展示了如何在DjangoRESTFramework中使用ListSerializer来处理多个tags字段,并在创建TagGroup时关联它们。当接收到前端传来的数据后,会删除tags字段,然后创建TagGroup,并为每个tag创建对应的Tag对象。如果tags为空,将不会在企业微信中创建标签组。

被折叠的 条评论
为什么被折叠?



