Django REST framework 中的序列化器

在此之前定义一个序列化工具:

views中的的代码

from rest_framework.viewsets import ModelViewSet

from .models import BookInfo
from .serializers import BookInfoSerializers

class BookInfoViewSet(ModelViewSet):
    queryset = BookInfo.objects.all() # 取序列化模型
    serializer_class = BookInfoSerializers # 指定序列化的类

定制url

from django.conf.urls import url, include
from . import views

from rest_framework.routers import DefaultRouter

router = DefaultRouter()
router.register(r"books", views.BookInfoViewSet)

urlpatterns = [
    url(r‘^index/$‘, views.index),
]

urlpatterns += router.urls

访问路径配置

http://127.0.0.1:8000/app001/books/

定制普通的序列化类

已有的model数据类型如下所示:

class BookInfo(models.Model):
    btitle = models.CharField(max_length=20, verbose_name=‘名称‘)
    bpub_date = models.DateField(verbose_name=‘发布日期‘)
    bread = models.IntegerField(default=0, verbose_name=‘阅读量‘)
    bcomment = models.IntegerField(default=0, verbose_name=‘评论量‘)
    is_delete = models.BooleanField(default=False, verbose_name=‘逻辑删除‘)

    class Meta:
        db_table = ‘tb_books‘  # 指明数据库表名
        verbose_name = ‘图书‘  # 在admin站点中显示的名称
        verbose_name_plural = verbose_name  # 显示的复数名称

    def __str__(self):
        return self.btitle

继承serializers.Serializer的序列化器:

# 为以上的model定制一个序列化器

from rest_framework import serializers

class BookInfoSerializers(serializers.Serializer):
    """ 图书列表序列化器"""
    id = serializers.IntegerField(label="ID", read_only=True)
    btitle = serializers.CharField(label="名称", max_length=20)
    bpub_date = serializers.DateField(label=‘发布日期‘, required=False)
    bread = serializers.IntegerField(label=‘阅读量‘, required=False)
    bcomment = serializers.IntegerField(label=‘评论量‘, required=False)
    is_delete = serializers.BooleanField(label=‘逻辑删除‘, required=False)

演示效果(python manages.py shell的环境下运行):

# 查询图书的的对象

from app001.models import BookInfo

book = BookInfo.objects.all()[0]

# 构造序列化器
from app001.serializers import BookInfoSerializers

serializer = BookInfoSerializers(book)

# 获取序列化之后的属性
print(serializer.data)
 # 打印效果:
"""
{‘id‘: 1, ‘bpub_date‘: ‘1980-05-01‘, ‘btitle‘: ‘射雕英雄传‘, ‘is_delete‘: False, ‘bcomment‘: 34, ‘bread‘: 12}

"""

model类

class HeroInfo(models.Model):
    GENDER_CHOICES = (
        (0, ‘male‘),
        (1, ‘female‘)
    )
    hname = models.CharField(max_length=20, verbose_name=‘名称‘)
    hgender = models.SmallIntegerField(choices=GENDER_CHOICES, default=0, verbose_name=‘性别‘)
    hcomment = models.CharField(max_length=200, null=True, verbose_name=‘描述信息‘)
    hbook = models.ForeignKey(BookInfo, on_delete=models.CASCADE, verbose_name=‘图书‘)  # 外键
    is_delete = models.BooleanField(default=False, verbose_name=‘逻辑删除‘)

    class Meta:
        db_table = ‘tb_heros‘
        verbose_name = ‘英雄‘
        verbose_name_plural = verbose_name

    def __str__(self):
        return self.hname

序列化器

from rest_framework import serializers

class HeroInfoSerializers(serializers.Serializer):
    """英雄数据序列化器"""
    GENDER_CHOICES = (
        (0, ‘male‘),
        (1, ‘female‘)
    )
    # hname = models.CharField(max_length=20, verbose_name=‘名称‘)
    id = serializers.IntegerField(label=‘ID‘, read_only=True)
    # hgender = models.SmallIntegerField(choices=GENDER_CHOICES, default=0, verbose_name=‘性别‘)
    hgender = serializers.ChoiceField(choices=GENDER_CHOICES, label=‘性别‘, required=False)
    # hcomment = models.CharField(max_length=200, null=True, verbose_name=‘描述信息‘)
    hcomment = serializers.CharField(label=‘描述信息‘, max_length=200, required=False, allow_null=True)
    # hbook = models.ForeignKey(BookInfo, on_delete=models.CASCADE, verbose_name=‘图书‘)  # 外键
    hbook = serializers.PrimaryKeyRelatedField(label=‘图书‘, read_only=True)
    # is_delete = models.BooleanField(default=False, verbose_name=‘逻辑删除‘)

交互界面输出

# 查询英雄的对象

from app001.models import HeroInfo

hero = HeroInfo.objects.all()[0]
from app001.serializers import HeroInfoSerializers

hs = HeroInfoSerializers(hero)

print(hs.data)

"""

{‘hgender‘: 1, ‘id‘: 1, ‘hcomment‘: ‘降龙掌‘, ‘hbook‘: ‘射雕英雄传‘}

{‘hgender‘: 1, ‘id‘: 1, ‘hcomment‘: ‘降龙掌‘, ‘hbook‘: 1}

"""

此字段将被序列化为关联对象的主键。

(hbook = serializers.PrimaryKeyRelatedField(label=‘图书‘, read_only=True)

hbook = serializers.PrimaryKeyRelatedField(label=‘图书‘,queryset=BookInfo.objects.all()))

print(hs.data)

"""

{‘hgender‘: 1, ‘id‘: 1, ‘hcomment‘: ‘降龙掌‘, ‘hbook‘: 1}

"""

(hbook = serializers.StringRelatedField(label=‘图书‘))

print(hs.data)

"""

{‘hgender‘: 1, ‘id‘: 1, ‘hcomment‘: ‘降龙掌‘, ‘hbook‘: ‘射雕英雄传‘}

"""

(    hbook = serializers.SlugRelatedField(label=‘图书‘, read_only=True, slug_field=‘bpub_date‘)

{‘hbook‘: datetime.date(1980, 5, 1), ‘hcomment‘: ‘降龙掌‘, ‘hgender‘: 1, ‘id‘: 1}

(    hbook = BookInfoSerializers()

{‘hgender‘: 1, ‘hcomment‘: ‘降龙掌‘, ‘id‘: 1, ‘hbook‘: OrderedDict([(‘id‘, 1), (‘btitle‘, ‘射雕英雄传‘), (‘bpub_date‘, ‘1980-05-01‘), (‘bread‘, 12), (‘bcomment‘, 34), (‘is_delete‘, False)])}

(    hbook = BookRelateField(read_only="True"))

{‘hcomment‘: ‘降龙掌‘, ‘hbook‘: ‘Book: 1 射雕英雄传‘, ‘id‘: 1, ‘hgender‘: 1}

(    heroinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)  # 新增

测试命令

from app001.models import BookInfo

book = BookInfo.objects.all()[0]

# 构造序列化器
from app001.serializers import BookInfoSerializers

bs = BookInfoSerializers(book)

# 获取序列化之后的属性
print(bs.data)

{‘bread‘: 12, ‘is_delete‘: False, ‘bpub_date‘: ‘1980-05-01‘, ‘heroinfo_set‘: [1, 2, 3, 4, 5], ‘btitle‘: ‘射雕英雄传‘, ‘id‘: 1, ‘bcomment‘: 34}

from app001.serializers import BookInfoSerializers
data = {‘bpub_date‘: 123}
serializer = BookInfoSerializers(data=data)
serializer.is_valid()
serializer.errors
serializer.validated_data
 
from app001.serializers import BookInfoSerializers
data = {‘bpub_date‘: "1993-12-27", ‘btitle‘: ‘python‘}
serializer = BookInfoSerializers(data=data)
serializer.is_valid()
serializer.errors
serializer.validated_data

"""

OrderedDict([(‘btitle‘, ‘python‘), (‘bpub_date‘, datetime.date(1993, 12, 27))])

"""

验证失败报404异常

serializer.is_valid(raise_exception=True)

from rest_framework import serializers

class BookInfoSerializers(serializers.Serializer):
    """ 图书列表序列化器"""
    id = serializers.IntegerField(label="ID", read_only=True)
    btitle = serializers.CharField(label="名称", max_length=20)
    bpub_date = serializers.DateField(label=‘发布日期‘, required=False)
    bread = serializers.IntegerField(label=‘阅读量‘, required=False)
    bcomment = serializers.IntegerField(label=‘评论量‘, required=False)
    is_delete = serializers.BooleanField(label=‘逻辑删除‘, required=False)
    heroinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)  # 新增

    def validate_btitle(self, value):
        if ‘django‘ not in value.lower():
            raise serializers.ValidationError("图书不是关于Django的")
        return value

from app001.serializers import BookInfoSerializers

data = {‘bpub_date‘: "1993-12-27", ‘btitle‘: ‘python_django‘}

serializer = BookInfoSerializers(data=data)

serializer.is_valid()

serializer.errors

serializer.validated_data

"""

OrderedDict([(‘btitle‘, ‘python_django‘), (‘bpub_date‘, datetime.date(1993, 12, 27))])

"""

在序列化器中定义一个validate()在这个方法中定义的字段会在最后被验证;

from rest_framework import serializers

def about_django(value):
    if ‘django‘ not in value.lower():
        raise serializers.ValidationError("about_django中抛出图书不是关于Django的")

class BookInfoSerializers(serializers.Serializer):
    """ 图书列表序列化器"""
    id = serializers.IntegerField(label="ID", read_only=True)
    btitle = serializers.CharField(label="名称", max_length=20,validators=[about_django])
    bpub_date = serializers.DateField(label=‘发布日期‘, required=False)
    bread = serializers.IntegerField(label=‘阅读量‘, required=False)
    bcomment = serializers.IntegerField(label=‘评论量‘, required=False)
    is_delete = serializers.BooleanField(label=‘逻辑删除‘, required=False)
    heroinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)  # 新增

    def validate(self, attrs):
        bread = attrs[‘bread‘]
        bcomment = attrs[‘bcomment‘]
        if bread < bcomment:
            raise serializers.ValidationError(‘阅读量小于评论量‘)
        return attrs
>>> from app001.serializers import BookInfoSerializers
>>> data = {‘bcomment‘: 34, ‘bread‘: 12,‘bpub_date‘: "1993-12-27", ‘btitle‘: ‘python_django‘}
>>> serializer = BookInfoSerializers(data=data)
>>> serializer.is_valid()
False
>>> serializer.errors
{‘non_field_errors‘: [ErrorDetail(string=‘阅读量小于评论量‘, code=‘invalid‘)]}
>>> serializer.validated_data
{}
 

抛出异常:

>>> from app001.serializers import BookInfoSerializers
>>> data = {‘bcomment‘: 14, ‘bread‘: 12,‘bpub_date‘: "1993-12-27", ‘btitle‘: ‘ptython‘}
>>> serializer = BookInfoSerializers(data=data)
>>> serializer.is_valid()
False
>>> serializer.errors
{‘btitle‘: [ErrorDetail(string=‘about_django中抛出图书不是关于Django的‘, code=‘invalid‘)]}
>>> serializer.validated_data
{}
>>>

在序列化器类的内部定义一个方法,来验证字段的属性(注意定义的函数的结构);

from rest_framework import serializers

class BookInfoSerializers(serializers.Serializer):
    """ 图书列表序列化器"""
    id = serializers.IntegerField(label="ID", read_only=True)
    btitle = serializers.CharField(label="名称", max_length=20,validators=[about_django])
    bpub_date = serializers.DateField(label=‘发布日期‘, required=False)
    bread = serializers.IntegerField(label=‘阅读量‘, required=False)
    bcomment = serializers.IntegerField(label=‘评论量‘, required=False)
    is_delete = serializers.BooleanField(label=‘逻辑删除‘, required=False)
    heroinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)  # 新增

    def validate_btitle(self, value):
        if ‘django‘ not in value.lower():
            raise serializers.ValidationError("图书不是关于Django的")
        return value

验证成功:

>>> from app001.serializers import BookInfoSerializers
>>> data = {‘bcomment‘: 10, ‘bread‘: 12,‘bpub_date‘: "1993-12-27", ‘btitle‘: ‘python_django‘}
>>> serializer = BookInfoSerializers(data=data)
>>> serializer.is_valid()
True
>>> serializer.errors
{}
>>> serializer.validated_data
OrderedDict([(‘btitle‘, ‘python_django‘), (‘bpub_date‘, datetime.date(1993, 12, 27)), (‘bread‘, 12), (‘bcomment‘, 10)])
>>>

验证失败:

>>> from app001.serializers import BookInfoSerializers
>>> data = {‘bcomment‘: 10, ‘bread‘: 12,‘bpub_date‘: "1993-12-27", ‘btitle‘: ‘ptython‘}
>>> serializer = BookInfoSerializers(data=data)
>>> serializer.is_valid()
False
>>> serializer.errors
{‘btitle‘: [ErrorDetail(string=‘图书不是关于Django的‘, code=‘invalid‘)]}
>>> serializer.validated_data
{}
 

在序列化器的外部定义一个方法,将该方法加入到字段中作为字段的验证方法

from rest_framework import serializers

def about_django(value):
    if ‘django‘ not in value.lower():
        raise serializers.ValidationError("图书不是关于Django的")

class BookInfoSerializers(serializers.Serializer):
    """ 图书列表序列化器"""
    id = serializers.IntegerField(label="ID", read_only=True)
    btitle = serializers.CharField(label="名称", max_length=20,validators=[about_django])
    bpub_date = serializers.DateField(label=‘发布日期‘, required=False)
    bread = serializers.IntegerField(label=‘阅读量‘, required=False)
    bcomment = serializers.IntegerField(label=‘评论量‘, required=False)
    is_delete = serializers.BooleanField(label=‘逻辑删除‘, required=False)
    heroinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)  # 新增

    def validate_btitle(self, value):
        if ‘django‘ not in value.lower():
            raise serializers.ValidationError("图书不是关于Django的")
        return value

    def validate(self, attrs):
        bread = attrs[‘bread‘]
        bcomment = attrs[‘bcomment‘]
        if bread < bcomment:
            raise serializers.ValidationError(‘阅读量小于评论量‘)
        return attrs

返回成功:

>>> from app001.serializers import BookInfoSerializers
>>> data = {‘bcomment‘: 10, ‘bread‘: 12,‘bpub_date‘: "1993-12-27", ‘btitle‘: ‘ptython_django‘}
>>> serializer = BookInfoSerializers(data=data)
>>> serializer.is_valid()
True
>>> serializer.errors
{}
>>> serializer.validated_data
OrderedDict([(‘btitle‘, ‘ptython_django‘), (‘bpub_date‘, datetime.date(1993, 12, 27)), (‘bread‘, 12), (‘bcomment‘, 10)])

返回失败:

>>> from app001.serializers import BookInfoSerializers
>>> data = {‘bcomment‘: 10, ‘bread‘: 12,‘bpub_date‘: "1993-12-27", ‘btitle‘: ‘ptython‘}
>>> serializer = BookInfoSerializers(data=data)
>>> serializer.is_valid()
False
>>> serializer.errors
{‘btitle‘: [ErrorDetail(string=‘about_django中抛出图书不是关于Django的‘, code=‘invalid‘)]}
>>> serializer.validated_data
{}

验证顺序:

验证顺序:

1,model字段本身;

2,字段中定义的validators;

3,序列化器中定义的对字段的验证方法validate_字段名;

4, 序列话器中validate的方法。

单字段唯一;

from rest_framework.validators import UniqueValidator

slug = SlugField(
    max_length=100,
    validators=[UniqueValidator(queryset=BlogPost.objects.all())]
)
 

联合唯一;

from rest_framework.validators import UniqueTogetherValidator

class ExampleSerializer(serializers.Serializer):
# ...
class Meta:
validators = [
UniqueTogetherValidator(
queryset=ToDoItem.objects.all(),
fields=(‘list‘, ‘position‘)
)
]

序列化后的数据保存

验证未通过程序包报错:

>>> from app001.serializers import BookInfoSerializers
>>> data = {‘btitle‘: ‘封神演义‘}
>>> serializer = BookInfoSerializers(data=data)
>>> serializer.is_valid()
False
>>> serializer.save()
Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/python/.virtualenvs/djf/lib/python3.5/site-packages/rest_framework/serializers.py", line 184, in save
    ‘You cannot call `.save()` on a serializer with invalid data.‘
AssertionError: You cannot call `.save()` on a serializer with invalid data.

验证通过并保存

>>> from app001.serializers import BookInfoSerializers
>>> data = {‘bcomment‘: 10, ‘bread‘: 12,‘bpub_date‘: "1993-12-27", ‘btitle‘: ‘ptython_django‘}
>>> serializer = BookInfoSerializers(data=data)
>>> serializer.is_valid()
True
>>> serializer.save()
<BookInfo: ptython_django>

序列化器的定义

from rest_framework import serializers

def about_django(value):
    if ‘django‘ not in value.lower():
        raise serializers.ValidationError("about_django中抛出图书不是关于Django的")

class BookInfoSerializers(serializers.Serializer):
    """ 图书列表序列化器"""
    id = serializers.IntegerField(label="ID", read_only=True)
    btitle = serializers.CharField(label="名称", max_length=20, validators=[about_django])
    bpub_date = serializers.DateField(label=‘发布日期‘, required=False)
    bread = serializers.IntegerField(label=‘阅读量‘, required=False)
    bcomment = serializers.IntegerField(label=‘评论量‘, required=False)
    is_delete = serializers.BooleanField(label=‘逻辑删除‘, required=False)
    heroinfo_set = serializers.PrimaryKeyRelatedField(read_only=True, many=True)  # 新增

    def validate_btitle(self, value):
        if ‘django‘ not in value.lower():
            raise serializers.ValidationError("图书不是关于Django的")
        return value

    def create(self, validated_data):
        """新建"""
        return BookInfo.objects.create(**validated_data)

    def update(self, instance, validated_data):
        """更新,instance为要更新的对象实例"""
        instance.btitle = validated_data.get(‘btitle‘, instance.btitle)
        instance.bpub_date = validated_data.get(‘bpub_date‘, instance.bpub_date)
        instance.bread = validated_data.get(‘bread‘, instance.bread)
        instance.bcomment = validated_data.get(‘bcomment‘, instance.bcomment)
        instance.save()
        return instance
 

成功创建对象

>>> from app001.serializers import BookInfoSerializers
>>> # from app001.models import BookInfo
>>> # book = BookInfo.objects.filter(btitle="ptython_django")[0]
>>> book = BookInfo.objects.get(id=10)
>>> data = {‘bcomment‘: 10, ‘bread‘: 12,‘bpub_date‘: "1994-12-27", ‘btitle‘: ‘ptython_django‘}
>>> # data = {‘bpub_date‘: "1994-12-27",‘bcomment‘: 10, ‘bread‘: 12,}
>>> serializer = BookInfoSerializers(book, data=data)
>>> serializer.is_valid()
True
>>> serializer.save()
<BookInfo: ptython_django>
>>> book.btitle
‘ptython_django‘
>>>
 

成功修改对象传入对象中的属性;

>>> from app001.serializers import BookInfoSerializers
>>> from app001.models import BookInfo
>>> book = BookInfo.objects.filter(btitle="ptython_django")[0]
>>> data = {‘bcomment‘: 10, ‘bread‘: 12,‘bpub_date‘: "1995-12-27", ‘btitle‘: ‘ptython_django‘}
>>> serializer = BookInfoSerializers(book, data=data)
>>> serializer.is_valid()
True
>>> serializer.save()
<BookInfo: ptython_django>
>>> book.btitle
‘ptython_django‘
>>> book.bpub_date
datetime.date(1995, 12, 27)

修改通过书名取到的的对象的值;

>>> from app001.serializers import BookInfoSerializers
>>> from app001.models import BookInfo
>>> book = BookInfo.objects.filter(btitle="ptython_django")[0]
>>> data = {‘bpub_date‘: "1996-12-27", ‘btitle‘: ‘ptython_django‘}
>>> serializer = BookInfoSerializers(book, data=data)
>>> serializer.is_valid()
True
>>> serializer.save()
<BookInfo: ptython_django>
>>> book.btitle
‘ptython_django‘
>>> book.bpub_date
datetime.date(1996, 12, 27)

原文地址:https://www.cnblogs.com/cerofang/p/9323140.html

时间: 2024-09-29 03:11:20

Django REST framework 中的序列化器的相关文章

Django REST framework 中文文档

参考链接: https://www.cnblogs.com/liwenzhou/p/8543035.html Django REST framework介绍 现在前后端分离的架构设计越来越流行,业界甚至出现了API优先的趋势. 显然API开发已经成为后端程序员的必备技能了,那作为Python程序员特别是把Django作为自己主要的开发框架的程序员, 我十分推荐Django REST framework(DRF)这个API框架. Django REST framework(DRF)框架文档齐全,社

javaScript中JSON序列化器/解析器

在JSON库中有一个全局的JSON对象, 包括两2个方法:序列化器即parse() 和 解析器stringify() 下面就介绍一个这两个方法的使用: 1.parse()用于将JSON字符串解析为对象或数组 var jsonText = '{"userName":"zhangsan","password":"123456"}';//注:  每个属性名和值都要用双引号, 单引号写在外面, 否则会出现异常. var changeJ

Django Rest Framework --- 序列化组件

一.序列化组件的作用 在前后端分离开发时,前端与后端用来交互的数据的格式是一致的(数据格式为字符串的json数据),于是后端程序员在传递数据时,便要将数据封装成符合格式的数据,如果不借助方法,手动进行数据封装,会非常的浪费时间,在Django rest framework中的序列化组件帮我们解决了这个问题. 二.Django自带的序列化组件 from django.core import serializers def test(request): book_list = Book.object

Django Rest Framework(2)-----序列化详解(serializers)

REST framework中的序列化类与Django的Form和ModelForm类非常相似.我们提供了一个Serializer类,它提供了一种强大的通用方法来控制响应的输出,以及一个ModelSerializer类,它为创建处理模型实例和查询集的序列化提供了有效的快捷方式. Serializers 序列化器允许把像查询集和模型实例这样的复杂数据转换为可以轻松渲染成JSON,XML或其他内容类型的原生Python类型.序列化器还提供反序列化,在验证传入的数据之后允许解析数据转换回复杂类型.不仅

DRF (Django REST framework) 框架介绍(2)

环境安装与配置 DRF需要以下依赖: Python (2.7, 3.2, 3.3, 3.4, 3.5, 3.6) Django (1.10, 1.11, 2.0) DRF是以Django扩展应用的方式提供的,所以我们可以直接利用已有的Django环境而无需从新创建.(若没有Django环境,需要先创建环境安装Django) 1. 安装DRF pip install djangorestframework 2. 添加rest_framework应用 我们利用在Django框架学习中创建的demo工

DRF (Django REST framework) 框架介绍

Web应用模式 在开发Web应用中,有两种应用模式: 前后端不分离 前后端分离 1 前后端不分离 在前后端不分离的应用模式中,前端页面看到的效果都是由后端控制,由后端渲染页面或重定向,也就是后端需要控制前端的展示,前端与后端的耦合度很高. 这种应用模式比较适合纯网页应用,但是当后端对接App时,App可能并不需要后端返回一个HTML网页,而仅仅是数据本身,所以后端原本返回网页的接口不再适用于前端App应用,为了对接App后端还需再开发一套接口. 2 前后端分离 在前后端分离的应用模式中,后端仅返

Django 学习之Django Rest Framework(DRF)

一. WEB应用模式 在开发Web应用中,有两种应用模式 1. 前后端不分离 2. 前后端分离 二. API接口 为了在团队内部形成共识.防止个人习惯差异引起的混乱,我们需要找到一种大家都觉得很好的接口实现规范,而且这种规范能够让后端写的接口,用途一目了然,减少双方之间的合作成本. 目前市面上大部分公司开发人员使用的接口服务架构主要有:restful.rpc. 1. rpc rpc: 翻译成中文:远程过程调用[远程服务调用]. http://www.example.com/api post请求

Cf序列化器-Serializer解析

Cf序列化器-Serializer 定义序列化器 Django REST framework中的Serializer使用类来定义,须继承自rest_framework.serializers.Serializer. 例如,我们已有了一个数据库模型类BookInfo class BookInfo(models.Model): btitle = models.CharField(max_length=20, verbose_name='名称') bpub_date = models.DateFiel

16-DRF工程搭建与序列化器

1.DRF工程搭建 环境安装与配置 DRF是以Django扩展应用的方式提供的,所以我们可以直接利用Django环境,而无需创建(先创建Django环境). 1.安装DRF pip3 install djangorestframework 2.添加rest_framework应用 在django工程上的settings.py的INSTALLED_APPS中添加“rest_framework” INSTALLED_APPS = [ ... 'rest_framework', ] 使用Django