1. 程式人生 > >DRF序列化

DRF序列化

efi field rom rfi serialize ins elf play title

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序列化