DRF序列化

Posted niuli1987

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了DRF序列化相关的知识,希望对你有一定的参考价值。

1. 安装

pip install djangoframework

2. app注册 rest_framework

INSTALLED_APPS = [
    django.contrib.admin,
    django.contrib.auth,
    django.contrib.contenttypes,
    django.contrib.sessions,
    django.contrib.messages,
    django.contrib.staticfiles,
    app.apps.AppConfig,
    ‘rest_framework‘
]

3. 自定义序列化程序,创建一个serializers序列器

serializer.CharField(source=‘orm操作‘)

from rest_framework import serializers

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

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

class BookS(serializers.Serializer):
    id = serializers.IntegerField()
    title = serializers.CharField(max_length=32)
    pub_time = serializers.DateField()
    category = serializers.IntegerField(source=get_category_display)

    publisher = PublisherS()
    authors = AuthorS(many=True)


4. views 中导入

from rest_framework.views import APIView
from rest_framework.response import Response
from app.models import Book
from .serializer import BookS

class BookView(APIView):
    def get(self,request):
        book_queryset = Book.objects.all()
        #用序列器序列化出一个对象
        ser_obj = BookS(book_queryset,many=True)
        return Response(ser_obj.data)

    def post(self,request):
        ...

 


以上是关于DRF序列化的主要内容,如果未能解决你的问题,请参考以下文章

DRF视图

DRF视图 𵀝

drf框架 2 drf框架的请求生命周期(as_view和dispatch方法), 请求解析渲染响应异常, 序列化组件 ,ORM配置回顾(media文件配置),应用在settings.py中(代码片

DRF框架serializer之视图优化

drf序列化器之请求响应以及视图

DRF之序列化