前后端分离djangorestframework——序列化与反序列化数据

转载 https://www.cnblogs.com/Eeyhan/p/10416005.html

from django.db import models
 
# 使用这个可以提前声明表名,在使用外键约束时可以不用考虑表前后顺序
__all__ = ['Book', 'Publisher', 'Author']
 
 
# Create your models here.
 
class Book(models.Model):
    title = models.CharField(max_length=32, verbose_name='图书名称')
    CHOICES = ((1, 'python'), (2, 'GO'), (3, 'linux'))
    category = models.IntegerField(choices=CHOICES, verbose_name='图书类别')
    pub_time = models.DateField(verbose_name='出版时间')
    publisher = models.ForeignKey(to='Publisher', on_delete=None)
    author = models.ManyToManyField(to='Author')
 
    def __str__(self):
        return self.title
 
    class Meta:
        # 自定义数据库表名
        verbose_name_plural = 'book'
        db_table = verbose_name_plural
 
 
class Publisher(models.Model):
    title = models.CharField(max_length=32, verbose_name='出版社名称')
 
    def __str__(self):
        return self.title
 
    class Meta:
        verbose_name_plural = 'publish'
        db_table = verbose_name_plural
 
 
class Author(models.Model):
    name = models.CharField(max_length=32, verbose_name='作者名称')
 
    def __str__(self):
        return self.name
 
    class Meta:
        verbose_name_plural = 'author'
        db_table = verbose_name_plural
class BookView(View):
    def get(self, request):
        book_list = models.Book.objects.values('id', 'title','pub_time')
        book_list = list(book_list)
        ret = json.dumps(book_list, ensure_ascii=False)
        return HttpResponse(ret)
# coding:utf-8
from django.shortcuts import HttpResponse
from django.http import JsonResponse
from django.views import View
import json
# Create your views here.
from demo1 import models
 
 
class BookView(View):
    def get(self, request):
        book_list = models.Book.objects.values("id", "title", 'pub_time')
        book_list = list(book_list)
        # ret = json.dumps(book_list, ensure_ascii=False)
        # print(book_list)
        return JsonResponse(book_list, safe=False, json_dumps_params={'ensure_ascii': False})
class BookView(View):
    def get(self, request):
        book_list = models.Book.objects.values("id", "title", 'pub_time','publisher')
        book_list = list(book_list)
        ret = []
        for field in book_list:
            pub_id = field['publisher']
            publish_obj = models.Publisher.objects.filter(id=pub_id).first()
            field['publisher'] = {
                'id':pub_id,
                'title':publish_obj.title
            }
            ret.append(field)
 
        return JsonResponse(ret, safe=False, json_dumps_params={'ensure_ascii': False})
# coding:utf-8
from django.shortcuts import HttpResponse
from django.http import JsonResponse
from django.views import View
import json
# Create your views here.
from demo1 import models
from django.core import serializers
 
class BookView(View):
    def get(self,request):
        book_list = models.Book.objects.all()
        ret = serializers.serialize('json',book_list,ensure_ascii=False)
        return HttpResponse(ret)
from rest_framework import serializers


class PublishSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    title = serializers.CharField(max_length=32)


class AuthorSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField(max_length=32)


class BookSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    title = serializers.CharField(max_length=32)
    CHOICES = ((1, 'python'), (2, 'GO'), (3, 'linux'))
    category = serializers.ChoiceField(choices=CHOICES,source='get_category_display')
    pub_time = serializers.DateField()

    publisher = PublishSerializer()
    author = AuthorSerializer(many=True)
# coding:utf-8
from django.shortcuts import HttpResponse
from django.http import JsonResponse
from django.views import View
import json
# Create your views here.
from demo1 import models
from django.core import serializers

from rest_framework.views import APIView
from rest_framework.response import Response
from demo1.serializers import BookSerializer


class BookView(APIView):
    def get(self, request):
        book_list = models.Book.objects.all()
        ret = BookSerializer(book_list, many=True)
        return Response(ret.data)
from rest_framework import serializers
from demo1 import models


class PublishSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    title = serializers.CharField(max_length=32)


class AuthorSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField(max_length=32)



class BookSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=False)
    title = serializers.CharField(max_length=32)
    CHOICES = ((1, 'python'), (2, 'GO'), (3, 'linux'))
    category = serializers.ChoiceField(choices=CHOICES, source='get_category_display', read_only=True)

    w_category = serializers.ChoiceField(choices=CHOICES, write_only=True)
    pub_time = serializers.DateField()

    publisher = PublishSerializer(read_only=True)
    w_publish = serializers.IntegerField(write_only=True)
    author = AuthorSerializer(many=True, read_only=True)

    # 作者字段只需要传入一个列表对象
    w_author = serializers.ListField(write_only=True)

    def create(self, validated_data):
        book_obj = models.Book.objects.create(title=validated_data['title'],
                                              category=validated_data['w_category'],
                                              pub_time=validated_data['pub_time'],
                                              publisher_id=validated_data['w_publish'])
        book_obj.author.add(*validated_data['w_author'])
        return book_obj
# coding:utf-8
from django.shortcuts import HttpResponse
from django.http import JsonResponse
from django.views import View
import json
# Create your views here.
from demo1 import models
from django.core import serializers

from rest_framework.views import APIView
from rest_framework.response import Response
from demo1.serializers import BookSerializer


class BookView(APIView):
    def get(self, request):
        book_list = models.Book.objects.all()
        ret = BookSerializer(book_list, many=True)
        return Response(ret.data)

    def post(self, request):
        # post的数据不再是在request.POST里
        # 而在request.data
        print(request.data)
        serialize = BookSerializer(data=request.data)
        if serialize.is_valid():
            # save是存储
            serialize.save()
            return Response(serialize.validated_data)
        else:
            return Response(serialize.errors)
class BookEditView(APIView):
    def get(self, request, id):
        book_obj = models.Book.objects.filter(id=id).first()
        ret = BookSerializer(book_obj)
        return Response(ret.data)

    def put(self, request, id):
        book_obj = models.Book.objects.filter(id=id).first()
        # partial参数表示只对部分数据验证
        serialize = BookSerializer(book_obj, data=request.data, partial=True)
        print(book_obj)

        if serialize.is_valid():
            # save是存储
            serialize.save()
            return Response(serialize.validated_data)
        else:
            return Response(serialize.errors)
from rest_framework import serializers
from demo1 import models


class PublishSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    title = serializers.CharField(max_length=32)


class AuthorSerializer(serializers.Serializer):
    id = serializers.IntegerField()
    name = serializers.CharField(max_length=32)


bookdata = {
    "title": "kali linux 入门到入狱",
    "w_category": 3,
    "pub_time": "2019-02-08",
    "w_publish": 2,
    "w_author": [1, 2, 4]
}


class BookSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=False)
    title = serializers.CharField(max_length=32)
    CHOICES = ((1, 'python'), (2, 'GO'), (3, 'linux'))
    category = serializers.ChoiceField(choices=CHOICES, source='get_category_display', read_only=True)

    w_category = serializers.ChoiceField(choices=CHOICES, write_only=True)
    pub_time = serializers.DateField()

    publisher = PublishSerializer(read_only=True)
    w_publish = serializers.IntegerField(write_only=True)
    author = AuthorSerializer(many=True, read_only=True)

    # 作者字段只需要传入一个列表对象
    w_author = serializers.ListField(write_only=True)

    def create(self, validated_data):
        book_obj = models.Book.objects.create(title=validated_data['title'],
                                              category=validated_data['w_category'],
                                              pub_time=validated_data['pub_time'],
                                              publisher_id=validated_data['w_publish'])
        book_obj.author.add(*validated_data['w_author'])
        return book_obj

    def update(self, instance, validated_data):
        # 次数的instance就是图书表数据库对象
        # 以下字段的key值也同样必须使用上面的只写的属性key
        instance.title = validated_data.get('title',instance.title)
        instance.category = validated_data.get('w_category',instance.category)
        instance.pub_time = validated_data.get('pub_time',instance.pub_time)
        instance.publisher_id = validated_data.get('w_publish',instance.publisher_id)
        if validated_data.get('w_author'):
            instance.author.set(validated_data['w_author'])
        instance.save()
        return instance
class BookSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=False)
    title = serializers.CharField(max_length=32)
    CHOICES = ((1, 'python'), (2, 'GO'), (3, 'linux'))
    category = serializers.ChoiceField(choices=CHOICES, source='get_category_display', read_only=True)

    w_category = serializers.ChoiceField(choices=CHOICES, write_only=True)
    pub_time = serializers.DateField()

    publisher = PublishSerializer(read_only=True)
    w_publish = serializers.IntegerField(write_only=True)
    author = AuthorSerializer(many=True, read_only=True)

    # 作者字段只需要传入一个列表对象
    w_author = serializers.ListField(write_only=True)

    def create(self, validated_data):
        book_obj = models.Book.objects.create(title=validated_data['title'],
                                              category=validated_data['w_category'],
                                              pub_time=validated_data['pub_time'],
                                              publisher_id=validated_data['w_publish'])
        book_obj.author.add(*validated_data['w_author'])
        return book_obj

    def update(self, instance, validated_data):
        # 次数的instance就是图书表数据库对象
        # 以下字段的key值也同样必须使用上面的只写的属性key
        instance.title = validated_data.get('title', instance.title)
        instance.category = validated_data.get('w_category', instance.category)
        instance.pub_time = validated_data.get('pub_time', instance.pub_time)
        instance.publisher_id = validated_data.get('w_publish', instance.publisher_id)
        if validated_data.get('w_author'):
            instance.author.set(validated_data['w_author'])
        instance.save()
        return instance

    def validate_title(self, value):
        if 'python' not in value.lower():
            raise serializers.ValidationError('修改失败,内容必须包含python')
        return value

class BookSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=False)
    title = serializers.CharField(max_length=32)
    CHOICES = ((1, 'python'), (2, 'GO'), (3, 'linux'))
    category = serializers.ChoiceField(choices=CHOICES, source='get_category_display', read_only=True)

    w_category = serializers.ChoiceField(choices=CHOICES, write_only=True)
    pub_time = serializers.DateField()

    publisher = PublishSerializer(read_only=True)
    w_publish = serializers.IntegerField(write_only=True)
    author = AuthorSerializer(many=True, read_only=True)

    # 作者字段只需要传入一个列表对象
    w_author = serializers.ListField(write_only=True)

    def create(self, validated_data):
        book_obj = models.Book.objects.create(title=validated_data['title'],
                                              category=validated_data['w_category'],
                                              pub_time=validated_data['pub_time'],
                                              publisher_id=validated_data['w_publish'])
        book_obj.author.add(*validated_data['w_author'])
        return book_obj

    def update(self, instance, validated_data):
        # 次数的instance就是图书表数据库对象
        # 以下字段的key值也同样必须使用上面的只写的属性key
        instance.title = validated_data.get('title', instance.title)
        instance.category = validated_data.get('w_category', instance.category)
        instance.pub_time = validated_data.get('pub_time', instance.pub_time)
        instance.publisher_id = validated_data.get('w_publish', instance.publisher_id)
        if validated_data.get('w_author'):
            instance.author.set(validated_data['w_author'])
        instance.save()
        return instance

    def validate_title(self, value):
        if 'python' not in value.lower():
            raise serializers.ValidationError('修改失败,内容必须包含python')
        return value

    def validate(self, attrs):
        if attrs['w_publish'] == 1 and attrs['w_category'] == 1:
            return attrs
        else:
            raise serializers.ValidationError('分类和作者id必须一样')
def my_validate(value):
    if '敏感信息' in value.lower():
        raise serializers.ValidationError('不能含有敏感信息')
    else:
        return value


class BookSerializer(serializers.Serializer):
    id = serializers.IntegerField(required=False)
    title = serializers.CharField(max_length=32, validators=[my_validate])
    CHOICES = ((1, 'python'), (2, 'GO'), (3, 'linux'))
    category = serializers.ChoiceField(choices=CHOICES, source='get_category_display', read_only=True)

    w_category = serializers.ChoiceField(choices=CHOICES, write_only=True)
    pub_time = serializers.DateField()

    publisher = PublishSerializer(read_only=True)
    w_publish = serializers.IntegerField(write_only=True)
    author = AuthorSerializer(many=True, read_only=True)

    # 作者字段只需要传入一个列表对象
    w_author = serializers.ListField(write_only=True)

    def create(self, validated_data):
        book_obj = models.Book.objects.create(title=validated_data['title'],
                                              category=validated_data['w_category'],
                                              pub_time=validated_data['pub_time'],
                                              publisher_id=validated_data['w_publish'])
        book_obj.author.add(*validated_data['w_author'])
        return book_obj

    def update(self, instance, validated_data):
        # 次数的instance就是图书表数据库对象
        # 以下字段的key值也同样必须使用上面的只写的属性key
        instance.title = validated_data.get('title', instance.title)
        instance.category = validated_data.get('w_category', instance.category)
        instance.pub_time = validated_data.get('pub_time', instance.pub_time)
        instance.publisher_id = validated_data.get('w_publish', instance.publisher_id)
        if validated_data.get('w_author'):
            instance.author.set(validated_data['w_author'])
        instance.save()
        return instance

    def validate_title(self, value):
        if 'python' not in value.lower():
            raise serializers.ValidationError('修改失败,内容必须包含python')
        return value

    def validate(self, attrs):
        if attrs['w_publish'] == 1 and attrs['w_category'] == 1:
            return attrs
        else:
            raise serializers.ValidationError('出版社和作者id必须一样')
from rest_framework import serializers
from demo1 import models


class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Book
        fields = '__all__'
        depth = 1  # 表示外键查找层级
class BookSerializer(serializers.ModelSerializer):
    category = serializers.CharField(source="get_category_display") # 注意这里是CharField不是ChoicesField

    class Meta:
        model = models.Book
        fields = '__all__'
        depth = 1  # 表示外键查找层级
class BookSerializer(serializers.ModelSerializer):
    category_display = serializers.SerializerMethodField(read_only=True)
    authors = serializers.SerializerMethodField(read_only=True)
    publish_info = serializers.SerializerMethodField(read_only=True)

    def get_category_display(self, obj):
        return obj.get_category_display()

    def get_publish_info(self, obj):
        publish_obj = obj.publisher
        return {"id": publish_obj.id, 'title': publish_obj.title}

    def get_authors(self, obj):
        # obj是Book对象
        author_list = obj.author.all()
        return [{"id": author_obj.id, "name": author_obj.name} for author_obj in author_list]

    class Meta:
        model = models.Book
        fields = '__all__'
        # depth = 1  # 表示外键查找层级
        extra_kwargs = {
            "category": {"write_only": True},
            "publisher": {"write_only": True},
            "author": {"write_only": True},
        }
# coding:utf-8
from django.shortcuts import HttpResponse
from django.http import JsonResponse
from django.views import View
import json
# Create your views here.
from demo1 import models
from django.core import serializers

from rest_framework.views import APIView
from rest_framework.response import Response
from demo1.serializers import BookSerializer



class BookView(APIView):
    def get(self, request):
        book_list = models.Book.objects.all()
        ret = BookSerializer(book_list, many=True)
        return Response(ret.data)

    def post(self, request):
        # post的数据不再是在request.POST里
        # 而在request.data
        print(request.data)
        serialize = BookSerializer(data=request.data)
        if serialize.is_valid():
            # save是存储
            serialize.save()
            return Response(serialize.data)
        else:
            return Response(serialize.errors)


class BookEditView(APIView):
    def get(self, request, id):
        book_obj = models.Book.objects.filter(id=id).first()
        ret = BookSerializer(book_obj)
        return Response(ret.data)

    def put(self, request, id):
        book_obj = models.Book.objects.filter(id=id).first()
        # partial参数表示只对部分数据验证
        serialize = BookSerializer(book_obj, data=request.data, partial=True)

        if serialize.is_valid():
            # print(serialize.validated_data)
            # save是存储
            serialize.save()
            return Response(serialize.data)
        else:
            return Response(serialize.errors)

    def delete(self, request, id):
        book_obj = models.Book.objects.filter(id=id).exists()
        if not book_obj:
            return Response('不存在id为%s的数据,请重试' % id)
        else:
            models.Book.objects.filter(id=id).delete()
            return Response("删除成功")

视图CBV

补充

转载:https://blog.csdn.net/weixin_42820697/article/details/84066497

serializers.Serializer 序列化

①在对序列化器进行save()保存时,可以额外传递数据,这些数据可以在create()和update()中的validated_data参数获取到
serializer.save(owner=request.user)
②默认序列化器必须传递所有required的字段,否则会抛出验证异常。但是我们可以使用partial参数来允许部分字段更新
serializer = CommentSerializer(comment, data={‘content’: u’foo bar’},
partial=True)

模型类序列化器

class HeroInfoSerializer(serializers.Modelserializers)
class Meta:
1–model = 模型 # 指定序列化的数据从哪来
2–fields = [‘字段1’, ‘字段2’] # 指定序列化模型中的具体字段
3–fields = ‘all’ # 序列化所有字段
4–read_only_fields = (‘字段1’, ‘字段2’) # 仅用于序列化输入字段
5–exclude = (‘字段’) # 除了该字段其余的都序列化
6–extra_kwargs = { # 添加或修改原有的选项参数
‘bread’: {‘min_value’: 0, ‘required’: True}},
‘bcomment’: {‘max_value’: 0, ‘required’: True}},
}
7–depth = 1 # 生成层级嵌套,自动序列化它的上一级(BookInfo) 1:表示嵌套的层度 如果图书的属于某个作者,获取该英雄的书籍的作者信息,depth则为2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值