创建一个DjangRestFramework应用

  1. 创建一个Django项目,最终项目结构如下:

screenshot_1.png

  1. 安装djangorestframework
pip install djangorestframework
  1. 应用目录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)
  1. 项目目录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),
]
  1. 应用目录App下,models.py设计
from django.db import models


class Student(models.Model):
    name = models.CharField(max_length=32)
  1. 应用目录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__'
  1. 应用目录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
  1. postman调用效果如下:

screenshot_1.png

posted @ 2020-05-05 21:24  iread9527  阅读(114)  评论(0编辑  收藏  举报