1.按照之前的方法创建Django项目
在settings.py中的INSTALLED_APPS中添加'rest_framework'
其中创建模型中的models.py
from django.db import models
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=200)
author = models.CharField(max_length=50)
def __str__(self):
return self.title
2.关键步骤:
(1)在mainsite中创建一个新的模块serializers.py
from .models import Post
from rest_framework import serializers
class PostSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Post
fields = ('title', 'author')
修改视图views.py
#from rest_framework.response import Response
#from rest_framework.views import APIView
from rest_framework import viewsets
from .models import Post
from .serializers import PostSerializer
# Create your views here.
"""
class PostView(APIView):
def get(self, request):
Post_list = Post.objects.all()
serializer = PostSerializer(Post_list, many=True)
return Response(serializer.data)
"""
class PostViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited.
"""
queryset = Post.objects.all()
serializer_class = PostSerializer
组织API URLS,在restdemo/urls.py中
from django.contrib import admin
from rest_framework import routers
from mainsite import views
from django.urls import include, path
#add these line
router = routers.DefaultRouter()
router.register(r'posts', views.PostViewSet)
urlpatterns = [
path('admin/', admin.site.urls),
#path('posts/', views.PostView.as_view())
path('', include(router.urls)),
path('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]
上述views.py和urls.py中注释掉的是中配置API URLS的方法。
最终测试我们的API
python manage.py runserver
直接通过浏览器访问http://xxx.xxx.x.xx:8000/posts/
这样既可以通过http://xxx.xxx.x.xx:8000/admin直接访问后台管理系统,也可以通过api访问后台数据,用的是同一数据库