Installation
Install using pip
, including any optional packages you want...
pip install djangorestframework pip install markdown # Markdown support for the browsable API. pip install django-filter # Filtering support
...or clone the project from github.
git clone git@github.com:encode/django-rest-framework.git
Add 'rest_framework'
to your INSTALLED_APPS
setting.
INSTALLED_APPS = ( ... 'rest_framework', )
If you're intending to use the browsable API you'll probably also want to add REST framework's login and logout views. Add the following to your root urls.py
file.
urlpatterns = [ ... url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
Note that the URL path can be whatever you want, but you must include 'rest_framework.urls'
with the 'rest_framework'
namespace. You may leave out the namespace in Django 1.9+, and REST framework will set it for you.
Example
Let's take a look at a quick example of using REST framework to build a simple model-backed API.
We'll create a read-write API for accessing information on the users of our project.
Any global settings for a REST framework API are kept in a single configuration dictionary named REST_FRAMEWORK
. Start off by adding the following to your settings.py
module:
REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] }
Don't forget to make sure you've also added rest_framework
to your INSTALLED_APPS
.
We're ready to create our API now. Here's our project's root urls.py
module:
from django.conf.urls import url, include from django.contrib.auth.models import User from rest_framework import routers, serializers, viewsets # Serializers define the API representation. class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'is_staff') # ViewSets define the view behavior. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all() serializer_class = UserSerializer # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r'users', UserViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^', include(router.urls)), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
You can now open the API in your browser at http://127.0.0.1:8000/, and view your new 'users' API. If you use the login control in the top right corner you'll also be able to add, create and delete users from the system.
上面的配置完成后,可以访问单表数据,如果进行跨表访问,比如Foreignkey,还需要继续进行配置。用上面的配置方法配置多张表
# models.py from django.db import models # Create your models here. class Students(models.Model): name = models.CharField(max_length=32,verbose_name= '姓名') age = models.PositiveIntegerField(verbose_name='年龄') gender_choices = ( (0,'male'), (1,'female'), ) gender = models.IntegerField(choices=gender_choices,verbose_name='性别') addr = models.CharField(max_length=64,verbose_name='地址') clas = models.ForeignKey('Classes') class Classes(models.Model): cls_name = models.CharField(max_length=32,verbose_name='班级名') cls_types = ( (0,'普通班'), (1,'实验班'), (2,'VIP班') ) cls_type = models.IntegerField(choices=cls_types) teacher = models.ForeignKey('Teachers') class Teachers(models.Model): name = models.CharField(max_length=32)
rest_serializers.py
# rest_serializers.py from rest_framework import serializers from app import models # Serializers define the API representation. # class StudentsSerializer(serializers.HyperlinkedModelSerializer): #HyperlinkedModelSerializer层级的超链接 class StudentsSerializer(serializers.ModelSerializer): # class Meta: model = models.Students fields = ('name', 'age', 'gender', 'addr', 'clas') depth = 3 #表关系的深度 # class ClassesSerializer(serializers.HyperlinkedModelSerializer): class ClassesSerializer(serializers.ModelSerializer): class Meta: model = models.Classes fields = ('cls_name', 'cls_type', 'teacher') # class TeachersSerializer(serializers.HyperlinkedModelSerializer): class TeachersSerializer(serializers.ModelSerializer): class Meta: model = models.Teachers fields = ('name',)
rest_viewset.py
# rest_viewsets.py from app.rest_serializers import StudentsSerializer, ClassesSerializer, TeachersSerializer from rest_framework import viewsets from app import models # ViewSets define the view behavior. class StudentsViewSet(viewsets.ModelViewSet): queryset = models.Students.objects.all() serializer_class = StudentsSerializer class ClassesViewSet(viewsets.ModelViewSet): queryset = models.Classes.objects.all() serializer_class = ClassesSerializer class TeachersViewSet(viewsets.ModelViewSet): queryset = models.Teachers.objects.all() serializer_class = TeachersSerializer
root_urls.py
root_urls.py from django.conf.urls import url, include from django.contrib import admin from app import views from rest_framework import routers from app import rest_viewsets # Routers provide an easy way of automatically determining the URL conf. router = routers.DefaultRouter() router.register(r'stu', rest_viewsets.StudentsViewSet) router.register(r'cls', rest_viewsets.ClassesViewSet) router.register(r'tea', rest_viewsets.TeachersViewSet) # Wire up our API using automatic URL routing. # Additionally, we include login URLs for the browsable API. urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'index',views.index), url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')), url(r'^api/', include(router.urls)), ]
settings.py
# settings.py INSTALLED_APPS = [ ... 'rest_framework', ] # 权限配置 REST_FRAMEWORK = { # Use Django's standard `django.contrib.auth` permissions, # or allow read-only access for unauthenticated users. 'DEFAULT_PERMISSION_CLASSES': [ 'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly' ] }