. _ _ _ _RESTframwork(Serializer介绍)

简介

实现序列化经常用到的三个模块
1.HyperLinkedModelSerializer 带超链接的序列化,是根据pk实现的,和贫困去关联,lookup_field = 'pk'
2.serializers.Serializer 可以实现自定义序列化
3.经常用到的就是serializer. ModelViewSet

实现流程

  • 创建序列化器
    • 将Json转成模型
    • 将模型转成Json
  • 创建了ViewSet
    • View的集合
    • 快捷生成增删改查的多种操作
  • 创建路由器
    • 自定的路由系统


    • 使用
      • API带界面可浏览
      • 也可以直接操作使用
      • 注册的路由直接提供了增删改查,还提供了详情


serializer

功能

  • 对象转成Dict
  • Dict转换成对象
  • 数据序列换与反序列化
  • HyperLinkedModelSerializer
  • 带超链接模型的序列化
    ModelSerializer
  • 模型直接序列化

models.py

from django.db import models

class Book(models.Model):

    b_name = models.CharField(max_length=16)
    b_price = models.FloatField(default=1)

1.创建serializer.py

from django.contrib.auth.models import User, Group
from rest_framework import serializers

from App.models import Book


class UserSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = User
        fields = ("url", "username", "email", "groups")


class GroupSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Group
        fields = ('url', "name")


class BookSerializer(serializers.HyperlinkedModelSerializer):

    class Meta:
        model = Book
        fields = ("url", "b_name", "b_price")

2.views.py

from django.contrib.auth.models import User, Group
from django.shortcuts import render
from rest_framework import viewsets

from App.models import Book
from App.serializers import UserSerializer, GroupSerializer, BookSerializer


class UserViewSet(viewsets.ModelViewSet):

    queryset = User.objects.all()

    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):

    queryset = Group.objects.all()

    serializer_class = GroupSerializer


class BookViewSet(viewsets.ModelViewSet):

    queryset = Book.objects.all()

    serializer_class = BookSerializer

App/urls.py

from rest_framework import routers

from App.views import UserViewSet, GroupViewSet, BookViewSet

router = routers.DefaultRouter()
router.register("users", UserViewSet)
router.register("groups", GroupViewSet)
router.register("books", BookViewSet)

url.py

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

from App.urls import router

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url(r'^app/', include(router.urls)),
]

你可能感兴趣的:(. _ _ _ _RESTframwork(Serializer介绍))