Django REST famework 序列化

BBigSun 评论193阅读模式

序列化(Serialization)实质将对象的状态信息转换为可存储或传输形式的过程。在客户端与服务端传输的数据形式主要分为两种:XML和JSON。在Django 中的序列化就是指将对象的状态信息转换为JSON数据,传送给前端。

API 调试工具:文章源自十年又十年-https://www.bbigsun.com/427.html

  • Postman
  • ApiFox

用 serializers.Serializer 方式序列化

1、安装文章源自十年又十年-https://www.bbigsun.com/427.html

pip install djangorestframework markdown django-filter

2、注册文章源自十年又十年-https://www.bbigsun.com/427.html

INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contentTypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'users.apps.UsersConfig',
    'rest_framework'
]

3、模型文章源自十年又十年-https://www.bbigsun.com/427.html

class Book(models.Model):
    """
    书籍信息
    """
    title = models.CharField(max_length=30, verbose_name='书名', default = '')
    isbn = models.CharField(max_length=30, verbose_name='isbn', default='')
    author = models.CharField(max_length=20, verbose_name='作者', default = '')
    publish = models.CharField(max_length=30, verbose_name='出版社', default = '')
    rate = models.FloatField(default=0, verbose_name='豆瓣评分')
    add_time = models.DateTimeField(default=datetime.now, verbose_name='添加时间')

    class Meta:
        verbose_name = '书籍信息'
        verbose_name_plural = verbose_name

def __str__(self):
    return self.title

迁移数据:文章源自十年又十年-https://www.bbigsun.com/427.html

python manage.py makemigrations
python manage.py migrate

4、序列化文章源自十年又十年-https://www.bbigsun.com/427.html

from rest_framework import serializers
from .models import UserProfile, Book

class BookSerializer(serializers.Serializer):
    title = serializers.CharField(required=True, max_length=100)
    isbn = serializers.CharField(required=True, max_length=100)
    author = serializers.CharField(required=True, max_length=100)
    publish = serializers.CharField(required=True, max_length=100)
    rate = serializers.FloatField(default=0)

5、API 视图(重要部分)文章源自十年又十年-https://www.bbigsun.com/427.html

from .serializers import BookSerializer
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import UserProfile, Book

class BookAPIView1(APIView):
    """
    使用Serializer
    """
    def get(self, request, format=None):
        APIKey = self.request.query_params.get("apikey", 0)
        developer = UserProfile.objects.filter(APIkey=APIKey).first()
        if developer:
            balance = developer.money
            if balance > 0:
                isbn = self.request.query_params.get("isbn", 0)
                books = Book.objects.filter(isbn=int(isbn))             # 对象状态信息
                books_serializer = BookSerializer(books, many=True)     # 转化为JSON数据
                developer.money -= 1
                developer.save()
                return Response(books_serializer.data)
            else:
                return Response("兄弟,又到了需要充钱的时候!好开心啊!")
        else:
            return Response("查无此人啊")

6、路由文章源自十年又十年-https://www.bbigsun.com/427.html

from django.contrib import admin
from django.urls import path
from users.views import BookAPIView1

urlpatterns = [
    path('admin/', admin.site.urls),
    path('apibook1/', BookAPIView1.as_view(), name='book1'),
]

用 serializers.ModelSerializer 方式序列化

from rest_framework import serializers
from .models import UserProfile, Book

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        Model = Book
        fields = '__all__'
文章源自十年又十年-https://www.bbigsun.com/427.html文章源自十年又十年-https://www.bbigsun.com/427.html

纸上得来终觉浅,绝知此事要躬行。

weinxin
17688689121
我的微信
微信扫一扫
BBigSun
  • 本文由 BBigSun 发表于 2023年 4月 11日 17:54:52
  • 转载请务必保留本文链接:https://www.bbigsun.com/427.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定