1.安装项目依赖
pip install django pip install djangorestframework
2.创建django项目
django-admin startproject mysite
3.创建app
python manage.py startapp polls
4.创建model
from django.db import models class Book(models.Model): name = models.CharField(max_length=200) author = models.CharField(max_length=20) pub_date = models.DateTimeField('date published')
5.创建序列化类
from rest_framework import serializers from polls.models import Book class BookModelSerializer(serializers.ModelSerializer): class Meta: model = Book fields = "__all__"
6.创建视图
from rest_framework.viewsets import ModelViewSet from polls.models import Book from polls.serializers import BookModelSerializer class BookViewSet(ModelViewSet): queryset = Book.objects.all() serializer_class = BookModelSerializer
7.添加路由
polls/urls.py
from rest_framework.routers import DefaultRouter from polls import views router = DefaultRouter() router.register("book", views.BookViewSet, basename="book") urlpatterns = [ ] + router.urls
mysite/mysqite/urls.py
from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("polls/", include("polls.urls")) ]
8. 数据迁移
python manage.py makemigrate python manage.py migrate
9.启动项目
python manage.py runserver
标签:py,models,创建,polls,django,api,urls,import,drf From: https://www.cnblogs.com/navysummer/p/16633517.html