工具为pycharm
pip install django-rest-framework
创建Django项目文件,名为DjangoRestFramework。
同步数据库
python manage.py migrate
创建超级用户
python manage.py createsuperuser
创建app
python manage.py startapp quickstart
创建py文件DjangoRestFramework/quickstart/serializers.py,写入代码。
from django.contrib.auth.models import User, Group
from rest_framework import serializers
class UserSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = User
fields = ('url', 'username', 'email', 'groups')
class GroupSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Group
fields = ('url', 'name')
from django.contrib.auth.models import User, Group
from rest_framework import viewsets
from .serializers import UserSerializer, GroupSerializer
class UserViewSet(viewsets.ModelViewSet):
"""
API endpoint that allows users to be viewed or edited
"""
queryset = User.objects.all().order_by('-date_joined')
serializer_class = UserSerializer
class GroupViewSet(viewsets.ModelViewSet):
queryset = Group.objects.all()
serializer_class = GroupSerializer
打开DjangoRestFramework/urls.py文件,写入代码
from django.contrib import admin
from django.urls import path, include
from rest_framework import routers
from quickstart import views
router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)
urlpatterns = [
path(r'', include(router.urls)),
path(r'api-auth/', include('rest_framework.urls', namespace='rest_framework')),
path('admin/', admin.site.urls),
]
打开DjangoRestFramework/settings.py文件
在INSTALLED_APPS最后加入'rest_framework'
INSTALLED_APPS = [
...
'rest_framework',
]
python manage.py runserver