Django REST Framework
1,使用Django的视图序列化:
1,HttpResponse
2,JsonResponse
2,使用Django REST Framework 框架的序列化工具类。
1,安装:pip install djangorestframework
2,导入:from rest_framework import serializers
3,使用:class ArticleSerializer(serializers.Serializer):
...
起初我们只能使用json序列化传数据:
url:
from django.conf.urls import url from django.contrib import admin from app01 import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^article_list/', views.article_list), ]
第一版views:
from django.shortcuts import render,HttpResponse # Create your views here. from app01.models import Article # 第一版 import datetime def article_list(request): # 去数据库查询所有的文章数据 query_set = Article.objects.all().values("id","title","create_time","type", "school__name") print(query_set) # 序列化成json格式 # 1,先把时间对象转换成字符串格式 for i in query_set: print(i["create_time"]) i["create_time"] = i["create_time"].strftime("%Y-%m-%d") print(i["create_time"]) import json data = json.dumps(list(query_set),ensure_ascii=False) # dumps无法直接传入query_set这种格式,所以先转成list, # ensure_ascii = False 显示中文, return HttpResponse(data)
models:
from django.db import models # Create your models here. class Article(models.Model): title = models.CharField(max_length=32) create_time = models.DateTimeField() type = models.SmallIntegerField( choices=((1,"原创"),(2,"转载")), default=1 ) school = models.ForeignKey(to="School",on_delete=models.CASCADE) # 标签 tag = models.ManyToManyField(to="Tag") class School(models.Model): name = models.CharField(max_length=32) class Tag(models.Model): name = models.CharField(max_length=32)
由于sqlite中,直接在数据库中增加的datetime时间类型无法取出数据值,所以需要新建一个独立的insert_time文件进行时间格式转化。
insert_time.py:
import os if __name__ == '__main__': os.environ.setdefault("DJANGO_SETTINGS_MODULE","restfreeme.settings") import django django.setup() # 单独的py文件去导入数据,上面是必不可少的步骤,后面一个参数"restfreeme.settings" 是当前项目名称.settings from app01.models import Article import datetime article_list = Article.objects.all() for i in article_list: i.create_time = datetime.datetime.now() i.save() query_set = Article.objects.all().values("id", "title", "create_time", "type", "school__name") obj = Article.objects.first() ret = obj.type ret = obj.get_type_display() # 默认用法 get_type_display()可以获取当前choice的,第二个元素。
第二版:views:
# 第二版 def article_list(request): # 去数据库查询所有的文章数据 query_set = Article.objects.all().values("id","title","create_time","type","school") for i in query_set: school_obj = School.objects.filter(id=i["school"]).first() id = school_obj.id name = school_obj.name i["school"] = {"id":id,"name":name} # 将query_set中的school赋值为{"id":id,"name":name} 这种格式 # 返回 # print(query_set) return JsonResponse(list(query_set),safe=False) # JsonResponse默认传的参数是一个字典类型的数据,若是传其他数据类型,则需要加上safe = False
第三版views:
# 第三版 rest framework版 from rest_framework import serializers # class Frame(serializers.Serializer): # id = serializers.IntegerField() # title = serializers.CharField() # create_time = serializers.DateField() # type = serializers.IntegerField() # school = serializers.CharField(source="school.name") # source 如果是属性就直接返回,如果是方法则执行方法。 class Frame(serializers.ModelSerializer): type = serializers.CharField(source="get_type_display") class Meta: model = Article fields = "__all__" depth = 1 # 把关联的字段的表的所有字段逐层递归 # 官方不推荐超过10层 通俗的来说就是数据层数例如:[1,2,[4,]]这样就是有两层, # 所以如果想查到内层的列表就可以写 depth = 1 ,依次类推。 def article_list(request): # 去数据库中查询所有文章数据 query_set = Article.objects.all() # print(query_set) change_data = Frame(query_set,many=True) print(change_data) # Frame(<QuerySet [<Article: Article object>, <Article: Article object>]>, many=True): # id = IntegerField(label='ID', read_only=True) # type = CharField(source='get_type_display') # title = CharField(max_length=32) # create_time = DateTimeField(read_only=True) # school = NestedSerializer(read_only=True): # id = IntegerField(label='ID', read_only=True) # name = CharField(max_length=32) # tag = NestedSerializer(many=True, read_only=True): # id = IntegerField(label='ID', read_only=True) # name = CharField(max_length=32) # 传入query_set类型,后面many=True意思是具有多个对象时,可加上,若是单个对象则不需要。 print(change_data.data) # 返回的是一个有序字典: # [OrderedDict([('id', 1), ('type', '原创'), ('title', '三国演义'), ('create_time', '2018-07-31T19:51:53.460497Z'), # ('school', OrderedDict([('id', 1), ('name', '北京')])), # ('tag', [OrderedDict([('id', 1), ('name', '历史')])])]), OrderedDict( # [('id', 2), ('type', '转载'), ('title', '西游记'), ('create_time', '2018-07-31T19:51:53.475487Z'), # ('school', OrderedDict([('id', 2), ('name', '上海')])), ('tag', [OrderedDict([('id', 2), ('name', '神话')])])])] # 返回 return JsonResponse(change_data.data,safe=False) def article_detail(request,id): article_obj = Article.objects.filter(id=id).first() # 筛选出一个文章对象。 json_detail = Frame(article_obj) return JsonResponse(json_detail.data)