1

S11 day 93 RestFramework 之 序列化

 

1. 表建模

 

from django.db import models

# Create your models here.

#文章表
class Article(models.Model):
    title =models.CharField(max_length=32)
    create_time =models.DateTimeField(auto_now_add=True)#第一次保存时间的日期.
    # update_time =models.DateTimeField(auto_now=True)#每次更新的时间
    type =models.SmallIntegerField(
        choices=((1,"原创"),(2,"转载")),
        default =1
      ) #文章的类型
    #来源
    school =models.ForeignKey(to="School",on_delete=models.CASCADE)#级联删除casecade
    tag =models.ManyToManyField(to="Tag")

#文章来源表
class School(models.Model):
    name =models.CharField(max_length=16)

# 文章标签表
class Tag(models.Model):
    name =models.CharField(max_length=16)

#评论
class Comment(models.Model):
    content=models.CharField(max_length=128)
    article =models.ForeignKey(to='Article',on_delete=models.CASCADE)

 

2. Url路由

 

from django.conf.urls import url,include
from django.contrib import admin
from app01 import views


urlpatterns = [
    # url(r"^api/",include(app01_url))


    url(r'^admin/', admin.site.urls),
    url(r'^article_list/', views.article_list),

 

 第一版序列化

 

from django.shortcuts import render,HttpResponse
from app01 import models
# Create your views here.


#第一版:
def article_list(request):
    # 去数据库查询所有的文章数据
    query_set=models.Article.objects.all().values("id","title")
    #序列化成json格式
    import json
    data=json.dumps(list(query_set),ensure_ascii=False)
    #返回.
    return HttpResponse(data)

 

输出结果:

 

 第二版序列化

 

# # 第二版
from django.http import JsonResponse
def article_list(request):
    # 去数据库查询所有的文章数据
    query_set=models.Article.objects.all().values("id","title","create_time","type")
    print("query_set",query_set)
    # JsonResponse序列化的时候如果不是字典要用safe关键字
    return JsonResponse(list(query_set),safe=False,)

 

输出结果:

query_set <QuerySet [{'id': 1, 'title': 'python文章', 'create_time': datetime.datetime(2018, 7, 31, 17, 10, 35, 690427, tzinfo=<UTC>), 'type': 1}, {'id': 2, 'title': 'go文章', 'create_time': datetime.datetime(2018, 7, 31, 17, 10, 35, 886304, tzinfo=<UTC>), 'type': 1}]>
[01/Aug/2018 15:45:34] "GET /article_list/ HTTP/1.1" 200 188

 

 

 第三版序列化

 

# # 第三版
from django.http import JsonResponse
from rest_framework import  serializers

class ArticleSerializer(serializers.Serializer):
    id =serializers.IntegerField()
    title =serializers.CharField()
    create_time=serializers.DateTimeField()
    type =serializers.CharField(source="get_type_display")
    school =serializers.CharField(source="school.name") #传了个属性
    tag =serializers.SerializerMethodField()
    #当choice字段和和FK 字段都可以用source获取值

    def get_tag(self,obj):
        print("====>",obj.tag.all())
        tag_list =[]
        for i in obj.tag.all():
           tag_list.append(i.name)
        return tag_list
#
def article_list(request):
    query_set=models.Article.objects.all()
    xbg =ArticleSerializer(query_set,many=True)
    print("===》",xbg.data)
    return JsonResponse(xbg.data,safe=False,)

 

输出结果:

print到的结果:

[01/Aug/2018 15:49:20] "GET /article_list/ HTTP/1.1" 200 368
====> <QuerySet [<Tag: Tag object>, <Tag: Tag object>]>
===》 [OrderedDict([('id', 1), ('title', 'python文章'), ('create_time', '2018-07-31T17:10:35.690427Z'), ('type', '原创'), ('school', '沙河校区'), ('tag', ['python tag', 'linux tag'])]), OrderedDict([('id', 2), ('title', 'go文章'), ('create_time', '2018-07-31T17:10:35.886304Z'), ('type', '原创'), ('school', '上海校区'), ('tag', ['python tag', 'linux tag'])])]

 

 

 

第四版序列化 

 

# 第四版 modelSeralizer
class ArticleModelSerilizer(serializers.ModelSerializer):
    type =serializers.CharField(source="get_type_display") #取到 1,或2里的值.
    class Meta:
        model =models.Article
        fields="__all__"
        depth =1


def article_list(request):
    query_set=models.Article.objects.all()
    xbg =ArticleModelSerilizer(query_set,many=True)
    print("===》",xbg.data)
    return JsonResponse(xbg.data,safe=False,)

 

输出结果:

[01/Aug/2018 15:53:14] "GET /article_list HTTP/1.1" 301 0
===》 [OrderedDict([('id', 1), ('type', '原创'), ('title', 'python文章'), ('create_time', '2018-07-31T17:10:35.690427Z'), ('school', OrderedDict([('id', 1), ('name', '沙河校区')])), ('tag', [OrderedDict([('id', 1), ('name', 'python tag')]), OrderedDict([('id', 2), ('name', 'linux tag')])])]), OrderedDict([('id', 2), ('type', '原创'), ('title', 'go文章'), ('create_time', '2018-07-31T17:10:35.886304Z'), ('school', OrderedDict([('id', 2), ('name', '上海校区')])), ('tag', [OrderedDict([('id', 1), ('name', 'python tag')]), OrderedDict([('id', 2), ('name', 'linux tag')])])])]
[01/Aug/2018 15:53:14] "GET /article_list/ HTTP/1.1" 200 482

 

 

posted @ 2018-08-01 15:52  萌哥-爱学习  阅读(228)  评论(0编辑  收藏  举报