创建一个DjangRestFramework应用
- 创建一个Django项目,最终项目结构如下:
- 安装djangorestframework
pip install djangorestframework
- 应用目录App下
urls.py
设计
# -*-coding:utf-8-*-
from rest_framework.routers import DefaultRouter
from App import views
router = DefaultRouter()
router.register(r'api/students', views.StudentViewSet)
- 项目目录DEFBlog下配置djangorestframework
- 4.1 配置
settings.py
, 将'rest_framework'加入到INSTALLED_APPS
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'App.apps.AppConfig',
'rest_framework',
]
- 4.2 配置
urls.py
from django.contrib import admin
from django.urls import path, include
from App.urls import router
urlpatterns = [
path('', include(router.urls)),
# path('admin/', admin.sitsse.urls),
]
- 应用目录App下,
models.py
设计
from django.db import models
class Student(models.Model):
name = models.CharField(max_length=32)
- 应用目录App下,
serializers.py
设计
# -*-coding:utf-8-*-
from rest_framework import serializers
from App.models import Student
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = '__all__'
- 应用目录App下,
views.py
# -*-coding:utf-8-*-
from rest_framework.viewsets import ModelViewSet
from App.models import Student
from App.serializers import StudentSerializer
class StudentViewSet(ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
- postman调用效果如下:
我在想我要不要写一句励志的话......