- 在项目的setting.py文件中 “INSTALLED_APPS“加入 ‘rest_framework‘
-
INSTALLED_APPS = ( ‘django.contrib.admin‘, ‘django.contrib.auth‘, ‘django.contrib.contenttypes‘, ‘django.contrib.sessions‘, ‘django.contrib.messages‘, ‘django.contrib.staticfiles‘, ‘rest_framework‘, ‘app01‘, )
其中,app01是我创建的一个app
3.在项目的urls.py文件中加入
from django.conf.urls import url, include from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = (‘url‘, ‘username‘, ‘email‘, ‘is_staff‘) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer router = routers.DefaultRouter() router.register(r‘users‘, UserViewSet) urlpatterns = [ url(r‘^‘, include(router.urls)), ]
这样就可以在首页匹配到rest-framework的api了
4.自己定义一个blog的api
在app01的models.py文件中创建Blog类:
from django.db import models # Create your models here. class Blog(models.Model): title = models.CharField(max_length = 50 ) content = models.TextField()
很简单的一个blog类,只有title和content 2个字段
app01下的api.py文件:
from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets from app01 import models from rest_framework import response class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = (‘url‘,‘username‘,‘email‘,‘is_staff‘) class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer class BlogSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = models.Blog depth = 1 fields = (‘url‘,‘title‘,‘content‘,) class BlogViewSet(viewsets.ModelViewSet): queryset = models.Blog.objects.all() serializer_class = BlogSerializer
api.py文件使用了rest-framework将User类和Blog类提供了api接口
修改urls.py文件,让user和blog2个资源可以api调用:
from django.conf.urls import include, url from django.contrib import admin from rest_framework import routers from app01 import api from app01 import views router = routers.DefaultRouter() router.register(r‘users‘, api.UserViewSet) router.register(r‘blogs‘, api.BlogViewSet) urlpatterns = [ url(r‘^admin/‘, include(admin.site.urls)), url(r‘^‘,include(router.urls)), ]
5.一开始blog为空,先开启django的后台管理
在app01下的models.py文件中加入:
from django.contrib import admin # Register your models here. from .models import Blog admin.site.register(Blog)
这样就可以用后台管理Blog了,当然,还得创建一个管理员账号密码,在项目的目录下执行:
python manage.py createsuperuser
输入要创建的账号密码即可
6.启动django程序,输入
直接到后台管理blog
没有数据,然后添加数据
添加了2条记录
上面是数据库的blog表
7.使用api查看blog数据
由于在urls.py中
url(r‘^‘,include(router.urls)),
这一句直接让rest framework处理所有的url,所以首页就可以看到我们在api.py中定义的user和
直接点链接blogs的,
在django中我们没有创建对数据库的查询操作和页面返回,但是调用rest framework标准的api接口我们就可以直接从数据库中查询到数据,增删改查都是可以的!实现起来如此简单!
时间: 2024-10-12 21:30:21