若是咱們想要使用序列化器對應的是Django的模型類,DRF爲咱們提供了ModelSerializer模型類序列化器來幫助咱們快速建立一個Serializer類。python
ModelSerializer與常規的Serializer相同,但提供了:shell
好比咱們建立一個BookInfoSerializerui
class BookInfoSerializer(serializers.ModelSerializer): """圖書數據序列化器""" class Meta: model = BookInfo fields = '__all__'
咱們能夠在python manage.py shell中查看自動生成的BookInfoSerializer的具體實現code
>>> from booktest.serializers import BookInfoSerializer >>> serializer = BookInfoSerializer() >>> serializer BookInfoSerializer(): id = IntegerField(label='ID', read_only=True) btitle = CharField(label='名稱', max_length=20) bpub_date = DateField(allow_null=True, label='發佈日期', required=False) bread = IntegerField(label='閱讀量', max_value=2147483647, min_value=-2147483648, required=False) bcomment = IntegerField(label='評論量', max_value=2147483647, min_value=-2147483648, required=False) image = ImageField(allow_null=True, label='圖片', max_length=100, required=False)
使用fields來明確字段,__all__
表名包含全部字段,也能夠寫明具體哪些字段,如圖片
class BookInfoSerializer(serializers.ModelSerializer): """圖書數據序列化器""" class Meta: model = BookInfo fields = ('id', 'btitle', 'bpub_date')
使用exclude能夠明確排除掉哪些字段get
class BookInfoSerializer(serializers.ModelSerializer): """圖書數據序列化器""" class Meta: model = BookInfo exclude = ('image',)
3) 顯示指明字段,如:it
class HeroInfoSerializer(serializers.ModelSerializer): hbook = BookInfoSerializer() class Meta: model = HeroInfo fields = ('id', 'hname', 'hgender', 'hcomment', 'hbook')
4) 指明只讀字段class
能夠經過read_only_fields指明只讀字段,即僅用於序列化輸出的字段test
class BookInfoSerializer(serializers.ModelSerializer): """圖書數據序列化器""" class Meta: model = BookInfo fields = ('id', 'btitle', 'bpub_date', 'bread', 'bcomment') read_only_fields = ('id', 'bread', 'bcomment')
咱們能夠使用extra_kwargs參數爲ModelSerializer添加或修改原有的選項參數import
class BookInfoSerializer(serializers.ModelSerializer): """圖書數據序列化器""" class Meta: model = BookInfo fields = ('id', 'btitle', 'bpub_date', 'bread', 'bcomment') extra_kwargs = { 'bread': {'min_value': 0, 'required': True}, 'bcomment': {'min_value': 0, 'required': True}, } # BookInfoSerializer(): # id = IntegerField(label='ID', read_only=True) # btitle = CharField(label='名稱', max_length=20) # bpub_date = DateField(allow_null=True, label='發佈日期', required=False) # bread = IntegerField(label='閱讀量', max_value=2147483647, min_value=0, required=True) # bcomment = IntegerField(label='評論量', max_value=2147483647, min_value=0, required=True)