明确什么是序列化
1. 把对象从内存中变成可存储或者传输的过程,(将序列化后内容写入磁盘或者通过网络传输到机器上)
2.把变量内容从序列化的对象重新读取到内存称为反序列化
在Django中,序列化器是将模型类型转换成json 或者XML格式数据并对数据进行校验具体表现在
1.Django从后台向前端传送数据时将模型类型转换成json格式数据返回给前端
2.前端向后台请求数据时对数据进行验证并进行处理数据(验证数据不一定处理,但是处理数据时必须先验证数据)
Django 框架中通过序列化器Serializer 进行操作
下面通过以json的格式进行返回数据
(Json是一种简单的数据交换格式,因为格式简洁,易于读取,这样前台就可以一眼就看出数据中的内容,方便检查排错同时可通过JavaScript进行解析,不管传输还是解析效率都很高,所以一般前台都会要求后台返回json格式的数据)
通过实例 Django 序列化器Serializer
#创建modles.py class Performer(models.Model): name = models.CharField(max_length=20) def __str__(self): return self.name class Meta: db_table='performer' class Type(models.Model): type = models.CharField(max_length=20) def __str__(self): return self.type class Meta: db_table ='type' class Film(models.Model): film_name = models.CharField(max_length=50,null=False) performer = models.ForeignKey(Performer,on_delete=models.CASCADE) film_type = models.ForeignKey(Type,on_delete=models.CASCADE) time = models.DateField() film_url = models.URLField() desc = models.TextField() def __str__(self): return self.film_name class Meta: db_table ='Film'
view视图
from django.shortcuts import render,HttpResponse
from app01 import models
from django.core import serializers
def index(request): # 这时是个QuerySet,里边是一个一个对象,无法json.dumps() movies =models.Film.objects.all() # 这时是个QuerySet,里边是一个一个字典 move_dict = models.Film.objects.values() # 这时是个QuerySet,里边是一个一个元组 move_tup = models.Film.objects.values_list('id','film_name') print(movies,type(movies)) #<QuerySet [<Film: 泰囧>, <Film: 功夫之王>, <Film: 澳门风云>]> <class 'type'> print(move_dict,type(move_dict))# <QuerySet [{'id': 1, 'film_name': '泰囧', 'performer_id': 1, 'film_type_id': 1, 'time': datetime.date(2020, 2, 3), 'film_url': 'http://baidu.com', 'desc': '1'}] print(move_tup,type(move_tup)) #<QuerySet [(1, '泰囧'), (2, '功夫之王'), (3, '澳门风云')]> <class 'type'> # 转换为列表 # file_list = list(move_dict) # for film in file_list: # print(film) #{'id': 1, 'film_name': '泰囧', 'performer_id': 1, 'film_type_id': 1, 'time': datetime.date(2020, 2, 3), 'film_url': 'http://baidu.com', 'desc': '1'} # per = film['performer_id'] # tp = film['film_type_id'] # per= models.Performer.objects.filter(id=per).first() # print(per) # typ =models.Type.objects.filter(id=tp).first() # print(typ) ret = serializers.serialize("json",movies)
ret = serializers.serialize("json",movies)
print(ret.encode('utf-8').decode('unicode_escape'))
"""
[{"model": "app01.film", "pk": 1, "fields": {"film_name": "泰囧", "performer": 1, "film_type": 1, "time": "2020-02-03", "film_url": "http://baidu.com", "desc": "1"}}, {"model": "app01.film", "pk": 2, "fields": {"film_name": "功夫之
王", "performer": 3, "film_type": 2, "time": "2020-02-01", "film_url": "http://baidu.com", "desc": "2"}}, {"model": "app01.film", "pk": 3, "fields": {"film_name": "澳门风云", "performer": 4, "film_type": 3, "time": "2020-01-16", "fi
lm_url": "http://baidu.com", "desc": "3"}}]
"""
return render(request,'index.html')