ModelSerializer

  • 先使用ModelSerializer测试一下结果,例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# 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依然是必填的,会提示
1
2
3
4
5
6
7
8
{
"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()