# 如果我们想要使用序列化器对应的是Django的模型类,DRF为我们提供了ModelSerializer模型类序列化器来帮助我们快速创建一个Serializer类
创建modelserializer序列化器
# 在serializer.py中创建序列器
# ModelSerializer模型序列化类
class TsSerializer(serializers.ModelSerializer):
class Meta:
# model 指定给那个模型类创建序列化器
model = TuShu
# 1. fields 指明序列化哪些字段
# {"tid": 1, "name": "喜喜", "riqi": "2022-01-03", "count": 1, "is_delete": true}
# fields = "__all__" # 返回全部字段
# {"tid": 1, "name": "喜喜"}
# fields = ('tid', "name") # 指定字段
# 2. exclude:排除
# {"tid": 1, "name": "\u559c\u559c", "riqi": "2022-01-03", "count": 1}
# exclude = ("is_delete",)
# 3. 指明那些字段只用于序列化输出,不用于反序列化
fields = "__all__"
read_only_fields = ("tid", "name", "riqi")
# 4. 额外参数 -->选项参数
extra_kwargs = {
"count": {"required": True, "min_value": 0}
}
视图调用
class TuShuView3(View):
def get(self, request):
qset = TuShu.objects.all()
# modelSerializer模型序列化器
ts = TsSerializer(instance=qset, many=True)
return JsonResponse(data=ts.data, safe=False)
配置路由
re_path(r"tushu3/$", TuShuView3.as_view(), name="tushu3")
标签:__,ModelSerializer,name,32,fields,tid,序列化
From: https://www.cnblogs.com/kh-1314/p/17148390.html