django-rest-framework快速入门

Requirements

  • python3.6
  • django2.0.6

工具为pycharm


Project

pip install django-rest-framework

创建Django项目文件,名为DjangoRestFramework。

同步数据库

python manage.py migrate

创建超级用户

python manage.py createsuperuser

创建app

python manage.py startapp quickstart

django-rest-framework快速入门_第1张图片

Serializers

创建py文件DjangoRestFramework/quickstart/serializers.py,写入代码。

django-rest-framework快速入门_第2张图片

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')

Views

打开DjangoRestFramework/quickstart/views.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):
    queryset = Group.objects.all()
    serializer_class = GroupSerializer


URLs

打开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),
]


Settings

打开DjangoRestFramework/settings.py文件

在INSTALLED_APPS最后加入'rest_framework'

INSTALLED_APPS = [
    ...
    'rest_framework',
]

END

python manage.py runserver

django-rest-framework快速入门_第3张图片


django-rest-framework快速入门_第4张图片








你可能感兴趣的:(Python,Django)