创建项目

创建一个tutorial的Django项目,并创建一个名为quickstart的新应用。

# 创建项目目录
mkdir tutorial
cd tutorial

# 创建虚拟环境
virtualenv env
source env/bin/activate  # windows使用env\Scripts\activate

# 虚拟环境中安装django和Django Rest Framework
pip install django
pip install djangorestframework

# 创建新项目及应用
django-admin.py startproject tutorial
cd tutorial
django-admin.py startapp quickstart

同步数据库
python manage.py migrate
创建管理员用户
python manage.py createsuperuser

序列化

首选需要定义一些序列化器,在tutorial/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 quickstart.serializers import UserSerializer, GroupSerializer


class UserViewSet(viewsets.ModelViewSet):

    queryset = User.objects.all().order_by('-date_joined')
    serializer_class = UserSerializer


class GroupViewSet(viewsets.ModelViewSet):

    queryset = Group.objects.all()
    serializer_class = GroupSerializer

路由

from django.contrib import admin
from django.urls import path
from django.conf.urls import include
from rest_framework import routers
from quickstart import views

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

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

settings.py

INSTALLED_APPS = [
    ...,
    "rest_framework",
    "quickstart"
]

测试api

首先通过命令行python manage.py runserver启动服务器。
浏览器直接访问http://127.0.0.1:8000/

0条评论

相关推荐

django教程

r

Django 2019-05-20 10:53:53

Celery

celery学习资料

Django 2019-05-25 18:41:55

django教程入门

适合django新人使用的学习手册

Django 2019-07-01 14:28:04

django实用资料

django项目从0到1自己总结的实用的资料,大部分常用的功能这里都有

Django 2019-05-08 18:21:34