环境安装与配置
DRF需要以下依赖:
- Python(3.5以上)
- Django(2.2以上)
DRF是以Django子应用的方式提供的,所以我们可以直接利用已有的Django环境而无需重新创建。
安装DRF
前提是安装了django。
$ pip install djangorestframework -i https://pypi.douban.com/simple
创建Django项目
进入创建项目的目录
$ django-admin startproject drf_base
使用pycharm打开项目,设置虚拟环境解析器,并修改manage.py中的后缀参数。
添加restframework应用
在项目的settings.py中添加:
INSTALLED_APPS = [
...
'rest_framework'
]
## Hello World
在djano项目中创建学生子应用,如果已经创建则无需创建。
```bash $ python manage.py startapp students ``` ### 创建模型类 ```python class Student(models.Model): """ 学生信息 """ name = models.CharField(max_length=255, verbose_name='姓名') sex = models.BooleanField(default=1, verbose_name='性别') age = models.IntegerField(verbose_name='年龄') classmate = models.CharField(max_length=5, verbose_name='班级编号') description = models.TextField(max_length=1000, verbose_name='个性签名')class Meta:
db_table = "tb_student"
verbose_name = '学生'
### 创建序列化器
```python
from rest_framework import serializers
from students.models import Student
class StudentModelSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = "__all__"
编写视图
from rest_framework.viewsets import ModelViewSet
from students.models import Student
from serializers import StudentModelSerializer
class StudentModelViewSet(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentModelSerializer
创建路由
from rest_framework.routers import DefaultRouter
from . import views
router = DefaultRouter()
router.register("students", views.StudentModelViewSet, basename="stu")
urlpatterns = [
] + router.urls
from django.urls import path, include
urlpatterns = [
path('api/', include("students.urls"))
]
标签:verbose,models,Django,restframework,import,class,name
From: https://www.cnblogs.com/Gazikel/p/17023315.html