serializer功能
序列化與反序列換
對(duì)象轉(zhuǎn)換成Dict
Dict轉(zhuǎn)換成對(duì)象
1.創(chuàng)建模型
from django.db import models
class Animal(models.Model):
a_name = models.CharField(max_length=32)
a_weight = models.FloatField(default=10)
class Spider(models.Model):
s_host = models.CharField(max_length=200)
class People(models.Model):
p_name = models.CharField(max_length=32)
p_age = models.IntegerField(default=18)
2.創(chuàng)建序繼承serializers.Serializer的列化器,必須實(shí)現(xiàn)抽象方法
必須實(shí)現(xiàn)抽象的方
alt+enter
alt+enter
序列化器寫法
Serializer
- 必須實(shí)現(xiàn)抽象方法
- update
- 更新
- create
- 創(chuàng)建
- 其余字段聲明
- Field
- 初始化屬性
- read_only 只讀(id)
- write_only 只寫 (密碼)
- required
- default
- initial
- source
- 映射(單個(gè)時(shí)候用不到枉阵,級(jí)聯(lián)的時(shí)候會(huì)用到)
- label
- help_text
- style
- error_messages 錯(cuò)誤信息
- validators 驗(yàn)證器
源碼
@property
def validators(self):
if not hasattr(self, '_validators'):
self._validators = self.get_validators()
return self._validators
@validators.setter
def validators(self, validators):
self._validators = validators
- allow_null 允許為空
- BooleanField
- 繼承Field
- 實(shí)現(xiàn)抽象方法
- to_internal_value
- to_representation
- IntegerField
- CharField
- 和ORM聲明非常像
- ModelSerializer
- 模型直接序列化
- HyperLinkedModelSerializer
- 模型序列化薪贫,添加超鏈接
from rest_framework import serializers
from SerializerLearn.models import Animal, Spider, People
# 生成序列化器
class AnimalSerializer(serializers.Serializer):
# read_only 只能讀
# POST提交用的
id = serializers.IntegerField(read_only=True)
a_name = serializers.CharField()
a_weight = serializers.FloatField()
def update(self, instance, validated_data):
instance.a_name = validated_data.get("a_name", instance.a_name)
instance.a_weight = validated_data.get("a_weight", instance.a_weight)
instance.save()
return instance
def create(self, validated_data):
return Animal.objects.create(**validated_data)
serializers.ModelSerializer繼承自serializers
多了一個(gè)映射,將模型屬性映射到serializer屬性
已經(jīng)將create方法和update方法(抽象方法)寫好了
注意: 如果有級(jí)聯(lián)就會(huì)拋異常
class SpiderSerializer(serializers.ModelSerializer):
class Meta:
model = Spider
fields = ("id", "s_host")
class PeopleSerializer(serializers.ModelSerializer):
class Meta:
model = People
fields = ("id", "p_name", "p_age")
對(duì)象轉(zhuǎn)字典
>>> from SerializerLearn.serializern import AnimalSerializer
>>> from SerializerLearn.models import Animal
>>> from SerializerLearn.serializers import AnimalSerializer
>>> animal = Animal.objects.get(pk=2)
>>> animal.a_name
'sssdf'
>>> animal
<Animal: Animal object>
>>> seriallizer = AnimalSerializer(animal)
>>> seriallizer.data
{'id': 2, 'a_name': 'sssdf', 'a_weight': 23.0}
>>> type(seriallizer.data)
<class 'rest_framework.utils.serializer_helpers.ReturnDict'>
>>>
views.py
獲取單個(gè)數(shù)據(jù)
獲取全部數(shù)據(jù)
添加數(shù)據(jù)
from django.http import JsonResponse, HttpResponse
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.views import APIView
from SerializerLearn.models import Animal, Spider, People
from SerializerLearn.serializers import AnimalSerializer, SpiderSerializer, PeopleSerializer
# 獲取全部和添加數(shù)據(jù)
@csrf_exempt
def animals(request):
if request.method == "GET":
animal_list = Animal.objects.all()
serializer = AnimalSerializer(animal_list, many=True)
return JsonResponse(serializer.data, safe=False)
elif request.method == "POST":
a_name = request.POST.get("a_name")
a_weight = request.POST.get("a_weight")
# 轉(zhuǎn)成字典
animal_data = {
"a_name": a_name,
"a_weight": a_weight,
}
serializer = AnimalSerializer(data=animal_data)
# 驗(yàn)證
if serializer.is_valid():
serializer.save()
return JsonResponse(serializer.data)
return JsonResponse({"msg": "create fial"})
# 獲取單個(gè)
def animal(request, pk):
if request.method == "GET":
animal_obj = Animal.objects.get(pk=pk)
serializer = AnimalSerializer(animal_obj)
return JsonResponse(serializer.data)
def spiders(request):
if request.method == "GET":
spider_list = Spider.objects.all()
serializer = SpiderSerializer(spider_list, many=True)
return JsonResponse(serializer.data, safe=False)
繼承自APIView會(huì)在下一章節(jié)
Response是RSTFul自己的功能很強(qiáng)大,下章節(jié)說(shuō)
class PeopleAPIView(APIView):
def get(self, request):
print(type(request))
peoples = People.objects.all()
serializer = PeopleSerializer(peoples, many=True)
return Response(data=serializer.data)
@api_view(["GET"])
def HelloAPIView(request):
print(type(request))
# return HttpResponse("haha")
data = {
"msg": "ok"
}
return Response(data)