Django REST framework创建项目--启动项目

3、启动项目
在目录xxx/selfManageDjango/selfManagePro/selfManage/firstapp 创建文件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')

在同目录下找到view.py,修改为:

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):
    """
    API endpoint that allows groups to be viewed or edited.
    """
    queryset = Group.objects.all()
    serializer_class = GroupSerializer
返回上一目录  既:xxx/selfManageDjango/selfManagePro/selfManage/,找到setting.py中增加分页,并加入rest_framework:
INSTALLED_APPS = [
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'rest_framework',
]
REST_FRAMEWORK = {
    'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination',
    'PAGE_SIZE': 10
}
在url.py中修改为:
from django.conf.urls import include, url
from django.contrib import admin
from rest_framework import routers
from firstapp import views

router = routers.DefaultRouter()
router.register(r'users', views.UserViewSet)
router.register(r'groups', views.GroupViewSet)

urlpatterns = [
    url(r'^admin/', admin.site.urls),
    url('', include(router.urls)),
    url('api-auth/', include('rest_framework.urls', namespace='rest_framework'))
]

最后我们运行:python manage.py runserver


屏幕快照 2019-02-01 下午5.35.42.png
屏幕快照 2019-02-01 下午5.35.55.png
屏幕快照 2019-02-01 下午5.51.44.png

你可能感兴趣的:(Django REST framework创建项目--启动项目)