二、DRF框架的使用(Django REST Framework)

1,所需依赖

Python(2.7,3.2,3.3,3.5,3.6)

Django(1.10,1.11,2.0)

2,安装DRF

pip  install  djangorestframework

3,配置DRF

setting.py

4,序列化器的定义

  a,可用字段

 

 

 

 b,选项参数

 

c. 通用参数

 

 

 

 d. 定义一个序列化器

model.py

serializers.py

e. Serializer的构造方法为:

      serializer = BookIndoSerializers(instance=None,data = data, **kwargs)

说明:

  1)用于序列化时,将模型类对象传入instance参数

  2)用于反序列化时,将要被反序列化的数据传入data参数

5、单表序列化器的序列化使用:

from booktest.serializers import BookInfoSerializer
from booktest.models import BookInfo

#单个数据序列化
book = BookInfo.objects.get(id=2)
serializer = BookInfoSerializer(book)
#获取序列化结果
data=serializer.data

#多数据的序列化
book_qs = BookInfo.objects.all()
serializer = BookInfoSerializer(book_qs, many=True)
data = serializer.data
Views.py

 

 6、单表序列化器的反序列

class BookInfoSerializer(serializers.Serializer):
"""图书数据序列化器"""
...

def create(self, validated_data):
"""新建"""
return BookInfo(**validated_data)

def update(self, instance, validated_data):
"""更新,instance为要更新的对象实例"""
instance.btitle = validated_data.get('btitle', instance.btitle)
instance.bpub_date = validated_data.get('bpub_date', instance.bpub_date)
instance.bread = validated_data.get('bread', instance.bread)
instance.bcomment = validated_data.get('bcomment', instance.bcomment)
return instance

zerializers.py

from db.serializers import BookInfoSerializer
data = {'btitle': '封神演义'}
serializer = BookInfoSerializer(data=data)
serializer.is_valid()  # True
serializer.save()  # <BookInfo: 封神演义>

    注意:

      默认序列化器必须传递所有required的字段,否则会抛出验证异常。但是我们可以使用partial参数来允许部分字段更新

      serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)

 7、一对多序列化器的使用:

class HeroInfoSerializer(serializers.Serializer):
"""英雄数据序列化器"""
GENDER_CHOICES = (
(0, 'male'),
(1, 'female')
)
id = serializers.IntegerField(label='ID', read_only=True)
hname = serializers.CharField(label='名字', max_length=20)
hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label='性别', required=False)
hcomment = serializers.CharField(label='描述信息', max_length=200, required=False, allow_null=True)


#1) PrimaryKeyRelatedField
#此字段将被序列化为关联对象的主键。
hbook = serializers.PrimaryKeyRelatedField(label='图书', read_only=True)

from booktest.serializers import HeroInfoSerializer
from booktest.models import HeroInfo
hero = HeroInfo.objects.get(id=6)
serializer = HeroInfoSerializer(hero)
serializer.data
# {'id': 6, 'hname': '乔峰', 'hgender': 1, 'hcomment': '降龙十八掌', 'hbook': 2}

#2) StringRelatedField
#此字段将被序列化为关联对象的字符串表示方式(即__str__方法的返回值)
hbook = serializers.StringRelatedField(label='图书')
#结果
#{'id': 6, 'hname': '乔峰', 'hgender': 1, 'hcomment': '降龙十八掌', 'hbook': '天龙八部'}

3)使用关联对象的序列化器
#hbook = BookInfoSerializer()
#结果
#{'id': 6, 'hname': '乔峰', 'hgender': 1, 'hcomment': '降龙十八掌', 'hbook': OrderedDict([('id', 2), ('btitle', '天龙八部')te', '1986-07-24'), ('bread', 36), ('bcomment', 40), ('image', None)])}

#4)SlugRelatedField
#此字段将被序列化为关联对象的指定字段数据
#hbook = serializers.SlugRelatedField(label='图书', read_only=True, slug_field='bpub_date')
#结果
#{'id': 6, 'hname': '乔峰', 'hgender': 1, 'hcomment': '降龙十八掌', 'hbook': datetime.date(1986, 7, 24)}

serializers.py

 

class UserSer(serializers.Serializer):
username = serializers.CharField(max_length=20)
age = serializers.IntegerField()
home = serializers.CharField(max_length=20)
hight = serializers.IntegerField()
classrooms = serializers.IntegerField(write_only=True)

def create(self, validated_data):


return demomodel.User.objects.create( classrooms_id=validated_data.pop('classrooms'),**validated_data) #获取数据里的classrooms外键ID,然后以classrooms_id的形式加进去。

serializer.py

 

8、多对多序列化器的使用:

class Student(models.Model):
name = models.CharField(max_length=32)

# 老师类
class Teacher(models.Model):
name = models.CharField(max_length=32)
stu = models.ManyToManyField(to='Student',related_name='teacher')

 

# 老师序列化
class TeacherSerializer(serializers.ModelSerializer):
class Meta:
model = Teacher
fields = ('id','name')

# 学生序列化
class StudentSerializer(serializers.Serializer):
name = serializers.CharField(max_length=32)
teacher = TeacherSerializer(many=True,read_only=True)

 


#######views.py#######

class ManyToManyTest(APIView):

def get(self, request):
studentobj = models.Student.objects.all()
stu = models.StudentSerializer(studentobj, many=True)
return Response(stu.data)


######结果#######
[
{
"name": "pp",
"teacher": [
{
"id": 1,
"name": "鹏鹏"
},
{
"id": 2,
"name": "月月"
}
]
},
{
"name": "peter",
"teacher": [
{
"id": 1,
"name": "鹏鹏"
}
]
}
]

serializers.py

 

class UserSer(serializers.Serializer):
username = serializers.CharField(max_length=20)
age = serializers.IntegerField()
home = serializers.CharField(max_length=20)
hight = serializers.IntegerField()
classrooms = serializers.IntegerField(write_only=True)
roles_list = serializers.ListField(write_only=True)

def create(self, validated_data):
data = validated_data.pop("roles_list")
user_onj = demomodel.User.objects.create( classrooms_id=validated_data.pop("classrooms"),**validated_data)
role_obj = demomodel.Role.objects.filter(id__in=data)

user_onj.roles.add(*role_obj)

return user_onj

serializers.py

posted @ 2021-09-22 16:57  Gavin_j  阅读(289)  评论(0编辑  收藏  举报