Django5+React18前后端分离开发实战05 序列化

Django REST Framework

We will use the Django REST Framework to help build our API.

我们会使用 Django REST Framework 框架来构建我们的API。

You can build APIs on your own in Django but it will take a lot of work.

你可以使用Django自己构建API,但是这会话费大量的工作。

The Django Rest Framework helps us quickly build reliable and secure APIs.

Django Rest Framework框架帮助我们构建可扩展的,安全的API接口。

There are a ton of documentation in the DRF site but thhis book will show you the best parts of the framework.

Django Rest Framework框架有非常完整的官方文档,但是我们在教程中只介绍其核心的部分。

Installation

Install DRF using pip:

使用pip安装DRF框架:

bash 复制代码
pip install djangorestframework

Next, add "rest_framework" to your INSTALLED_APPS setting in backend/settings.py.

接下来,在settings.py中配置应用:

python 复制代码
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "todo",
    "rest_framework",
]

Adding the API app

We create a dedicated api app to contain API specific files.

我们创建一个api应用,包含API相关的文件。

注意:这里我们不需要创建这个应用,所有代码都写在之前创建的todo应用中。

So in the Terminal, under backend, run the command.

所以,在backend目录下执行命令:

bash 复制代码
python manage.py startapp api

We'll need to add our new api app to INSTALLED_APPS.

In backend/backend/settings.py, add:

python 复制代码
INSTALLED_APPS = [
    "django.contrib.admin",
    "django.contrib.auth",
    "django.contrib.contenttypes",
    "django.contrib.sessions",
    "django.contrib.messages",
    "django.contrib.staticfiles",
    "todo",
    "rest_framework",
    "api",
]

To get started on our API, we declare Serializers which translate data from the Todo Model instances into JSON objects that is easy to consume over the Internet.

为了启动我们的API,我们需要定义一个序列化类。这个序列化类的主要作用是将模型对象转换为JSON对象。

The JSON objects are outputted at API endpoint urls.

API接口返回的时JSON类型的对象。

Django REST framework shops with a powerful built-in serializer class that we can quickly extend with some code.

DRF框架提供了内置的序列化类,方便我们快速的生成JSON序列化对象。

In the api folder, create the file serilizers.py with the following code.

在api目录中,我们创建serializers.py文件,编写如下代码。

注意:这里我们的代码实际上是写在 todo/serializers.py

python 复制代码
from rest_framework import serializers
from .models import Todo


class TodoSerializer(serializers.ModelSerializer):
    create_time = serializers.ReadOnlyField()
    update_time = serializers.ReadOnlyField()
    completed = serializers.ReadOnlyField()

    class Meta:
        model = Todo
        fields = ['id', 'title', 'detail', 'completed', 'create_time', 'update_time']

Code Explanation

python 复制代码
class TodoSerializer(serializers.ModelSerializer):

We extend DRF's ModelSerializer into a TodoSerializer class.

我们编写TodoSerializer类继承了DRF的ModelSerializer类。

ModelSerializer provides an API to create serializers from your model.

ModelSerializer类提供了根据模型创建序列化对象的接口。

python 复制代码
class Metal:
    model = Todo
    fields = ['id', 'title', 'detail', 'completed', 'create_time', 'update_time']

Under class Meta, we specify our database model Todo and the fields we want to expose i.e. ['id', 'title', 'detail', 'completed', 'create_time', 'update_time'].

通过Meta元类,我们指定了序列化类要暴露的字段类表:['id', 'title', 'detail', 'completed', 'create_time', 'update_time']。

Django REST Framework then magically transforms our model data into JSON, exposing these fields from our Todo model.

DRF框架通过这些字段,会自动将Todo模型类对象自动转换为JSON对象。

Fields not specified here will not be exposed in the API.

没有在这里指定的字段不会通过API暴露出去。

Remember that "id" is created automatically by Django so we didn't have to define it in Todo model.

记住id这个字段是Django自动创建的,所以我们不需要在Todo模型类中显式的声明。

But we will use it in our API.

但是我们会在API接口中使用它。

Often, an underlying database model will have more fields than what needs to be exposed.

通常,一个生产级别的数据库模型会比我们这里展示的要多得多。

DRF's serializer class's ability to include/exclude fields in our API is a great feature and makes it straightforward to control this.

DRF提供了include和exclude这两个字段,用来包含和排除指定的字段,使得当字段很多的时候,我们声明起来更加的简单。

Additionally,we specify that created and completed fields are read only.

另外,我们指定了几个只读的字段。

I.e., they cannot be edited by a user, because they ought to be auto-populated when a todo is created and when it is marked as complete.

这些字段在通过API交互的时候,只能通过GET获取,而不能通过POST和PUT等方法进行修改。

Now that we have our first serializer, let's see how to setup URLs for our API endpoints in the next chapter.

现在,我们有了第一个序列化类,接下来我们看看如何通过URL和API和前端进行交互吧。

相关推荐
互联网搬砖老肖27 分钟前
运维打铁: MongoDB 数据库集群搭建与管理
运维·数据库·mongodb
典学长编程1 小时前
数据库Oracle从入门到精通!第四天(并发、锁、视图)
数据库·oracle
蹦蹦跳跳真可爱5892 小时前
Python----OpenCV(图像増强——高通滤波(索贝尔算子、沙尔算子、拉普拉斯算子),图像浮雕与特效处理)
人工智能·python·opencv·计算机视觉
nananaij2 小时前
【Python进阶篇 面向对象程序设计(3) 继承】
开发语言·python·神经网络·pycharm
雷羿 LexChien2 小时前
从 Prompt 管理到人格稳定:探索 Cursor AI 编辑器如何赋能 Prompt 工程与人格风格设计(上)
人工智能·python·llm·编辑器·prompt
积跬步,慕至千里2 小时前
clickhouse数据库表和doris数据库表迁移starrocks数据库时建表注意事项总结
数据库·clickhouse
极限实验室2 小时前
搭建持久化的 INFINI Console 与 Easysearch 容器环境
数据库
敲键盘的小夜猫3 小时前
LLM复杂记忆存储-多会话隔离案例实战
人工智能·python·langchain
白仑色3 小时前
Oracle PL/SQL 编程基础详解(从块结构到游标操作)
数据库·oracle·数据库开发·存储过程·plsql编程
高压锅_12203 小时前
Django Channels WebSocket实时通信实战:从聊天功能到消息推送
python·websocket·django