序列化

models.py部分


from django.db import models


class Book(models.Model):
    title=models.CharField(max_length=32)
    price=models.IntegerField()
    pub_date=models.DateField()
    publish=models.ForeignKey("Publish")
    authors=models.ManyToManyField("Author")
    def __str__(self):
        return self.title

class Publish(models.Model):
    name=models.CharField(max_length=32)
    email=models.EmailField()
    def __str__(self):
        return self.name

class Author(models.Model):
    name=models.CharField(max_length=32)
    age=models.IntegerField()
    def __str__(self):
        return self.name

基于CBV写序列化数据接口


from app02.models import *
from django.shortcuts import render, HttpResponse
import json
class BookView(View):
	def get(self, request):
		queryset = Book.objects.all()
		temp = []
		for i in queryset:
			temp.append({“title”:i.title})
        ret=json.dumps(temp)
		return HttpResponse(ret)

django序列化接口


from app02.models import *
from django.shortcuts import render, HttpResponse
from django.core.serializers import serialize

class BookView(View):
def get(self, request):
    queryset = Book.objects.all()
    queryset = serialize("json", queryset)
return HttpResponse(queryset)

restframework的序列化接口


是个集成功能组件,到底用什么功能,取决于调什么接口。

  1. 兼具form组件的校验功能

Models部分:

from rest_framework import serializers
from app02.models import Publish, Book, Author, AuthorDetail

# serializers.ModelSerializer,使用可参照ModelForm
class PublishSerializers(serializers.ModelSerializer):
    class Meta:
        model = Publish
        fields = "__all__"

class BookSerializers(serializers.ModelSerializer):
    class Meta:
        model = Book
        # fields = "__all__"
        exclude = ("nid",)
   
     # 重写create方法
    def create(self, validated_data):
        authors = validated_data.pop("authors")
        print("="*120)
        print(authors)
        obj = Book.objects.create(**validated_data)
        obj.authors.add(*authors)
        return obj

    publish = serializers.CharField()
    # authors = serializers.SerializerMethodField()
    #
    # def get_authors(self, obj):
    #     temp = []
    #     for i in obj.authors.all():
    #         temp.append(str(i.pk))
    #     return ','.join(temp)

class AuthorSerializers(serializers.ModelSerializer):
    class Meta:
        model = Author
        exclude = ("nid", )

class AuthorDetailSerializers(serializers.ModelSerializer):
    class Meta:
        model = AuthorDetail
        exclude = ("nid", "birth")

# class BookSerializers(serializers.Serializer):
#     title = serializers.CharField()
#     create_at = serializers.DateTimeField()
#     publish_name = serializers.CharField(source="publish.name")
#     publish_city = serializers.CharField(source="publish.city")
#     authors = serializers.SerializerMethodField()
#
#     def get_authors(self, obj):
#         temp = []
#         for i in obj.authors.all():
#             author = []
#             author.append(i.pk)
#             author.append(i.name)
#             author.append(i.age)
#             temp.append(author)
#         return temp

views.py部分

from rest_framework import serializers
class BookSerializers(serializers.Serializer):
        # get方法
	def get(self, request):
            book_qs = Book.objects.all()
            bs = dataApi.BookSerializers(book_qs, many=True)
            return Response(bs.data)
	# post方法
	def post(self,request,*args,**kwargs):
            bs=BookSerializers(data=request.data,many=False)
            if bs.is_valid():
                bs.save()
                return Response(bs.data)
            else:
                return HttpResponse(bs.errors)
posted @ 2018-08-03 23:24  桥前石头  阅读(127)  评论(0编辑  收藏  举报