ModelSerializer
-
先使用
ModelSerializer
测试一下结果,例:# models.py ###### from django.db.models import Model, CharField, BooleanField, ForeignKey class TestModel(User): name = CharField(max_length=64, name='name') class TestModel(Model): status = BooleanField(default=False, name='status') user = ForeignKey(User, db_column="user_id", name='user', on_delete=CASCADE, related_name="user_test") ###### # seriailzer.py ###### from models import TestModel from rest_framework.serializers import ModelSerializer, IntegerField, Serializer from rest_framework.serializers import SerializerMethodField class TestSerializer(ModelSerializer): user = IntegerField(required=False) status = SerializerMethodField() class Meta: model = TestModel fields = ("id", "status", "uesr")
-
把外键user设置为了非必填,但是现在去调用post接口就会发现user依然是必填的,会提示
{ "detail": "This field is required.", "sub_detail": { "user": [ "This field is required." ] } }
Serializer
- 再使用
Serializer
测试一下结果。 - 代码就不在贴了,直接把serializer.py文件中的
class TestSerializer(ModelSerializer):
改为class TestSerializer(Serializer):
就可以了 - 这时就会发现再次调用接口就不会再出现问题了
区别
-
ModelSerializer
类和Serializer
类大致一样,不过添加了一些功能,可以更加便捷的去校验model
中的数据. -
ModelSerializer
会基于model
自动创建一些字段 -
ModelSerializer
会自动生成一些验证,比如unique_together
验证. -
ModelSerializer
包含简单的默认的create()
和update()
.