前提首先安装了django,安装方式:pip install django
1、 djangorestftamework安装:
pip install djangorestframework
2、 创建一个项目
django-admin startproject djangorestdemo
3、 创建应用
cd djangorestdemo
python manage.py startapp rest
4、 在settings.py里配置
REST_FRAMEWORK={ 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] }
5、在djangorestdemo/urls.py编写相关代码
#编写序列化类 from django.contrib import admin from django.urls import path from django.conf.urls import url, include from rest_framework import serializers,viewsets,routers from django.contrib.auth.models import User class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model=User fields=['url', 'username', 'email', 'is_staff'] #编写viewset视图集 class UserViewset(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer #注册路由信息 router=routers.DefaultRouter() router.register(r'users',UserViewset) #urlpatterns里添加路由 urlpatterns = [ url('admin/', admin.site.urls), url(r'^',include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
6、运行:python manage.py runserver
7、浏览器上访问接口
8、整个工程结构: