目录
1.新建项目和app
2.创建模型操作类
3.在settings.py中配置mysql数据库
4.数据库迁移
?5.创建序列化器
6.在stundents>views.py中编写如下代码:
7.新建子路由students>urls.py:
8.编辑总路由urls.py:
?9.查看api:
1.新建项目和app
django-admin startproject drfdemo
django-admin startapp students
在settings.py中添加标注区域代码
2.创建模型操作类
在students/models.py中添加如下代码:
from django.db import models
# Create your models here.
class Student(models.Model):
"""学生信息"""
name = models.CharField(max_length=255,verbose_name="姓名")
sex = models.BooleanField(default=1, verbose_name="性别")
age = models.IntegerField(verbose_name="年龄", help_text="年龄不能小于0")
classroom = models.CharField(max_length=5, verbose_name="班级编号")
description = models.TextField(max_length=1000, verbose_name="个性签名")
class Meta:
db_table = "tb_student"
verbose_name = "学生"
verbose_name_plural = verbose_name
3.在settings.py中配置mysql数据库
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': '数据库名',
'HOST':'ip地址',
'POST':3306,
'USER':'用户名',
'PASSWORD':'密码',
}
}
在主应用__init__.py中添加如下代码:
from pymysql import install_as_MySQLdb
install_as_MySQLdb()
4.数据库迁移
在navcat中查看是否创建成功:
?5.创建序列化器
在students中新建serializers.py
?serializers.py:
from rest_framework import serializers
from stuapi.models import Student
# 创建一个序列化器用于序列化和反序列化
class StudentModelSerializer(serializers.ModelSerializer):
class Meta:
model = Student # model指明该序列化器处理的数据字段从模型类参考生成
# fields = "__all__" # field指明该序列化器包含模型类中的哪些字段,“all”指明所有字段
fields = ["id","name","sex","age","classroom","description"] # 指定包含哪些字段
6.在stundents>views.py中编写如下代码:
from rest_framework.viewsets import ModelViewSet
from stuapi.models import Student
from .serializers import StudentModelSerializer
# Create your views here.
class StudentModelViewSet(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentModelSerializer
7.新建子路由students>urls.py:
urls.py:?
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register("stu", views.StudentModelViewSet, basename="stu"),
urlpatterns = [
] + router.urls
8.编辑总路由urls.py:
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('api/', include("students.urls")),
]
?9.查看api:
访问http://127.0.0.1:8000/api/:
?访问http://127.0.0.1:8000/api/stu/:
?访问http://127.0.0.1:8000/api/stu/2/:
对比Django 创建api的demo (不使用RESTFramework)发现使用RESTFramework更具有优势。
|