在开始之前需要下载: pip install djangorestframework
把应用添加进INSTALLED_APPS:
INSTALLED_APPS = (
...
'rest_framework',
)
配置:REST_FRAMEWORK = {
'DEFAULT_PERMISSION_CLASSES': [
'rest_framework.permissions.DjangoModelPermissionsOrAnonReadOnly'
]
}
序列化器:
序列器类似于表单,它指定将数据转换为何种格式。首先在Django项目里创建一个serializers.py文件,接着:
from django.contrib.auth.models import User
from rest_framework import serializers
class UserSerializer(serializers.ModelSerializer):
class Meta:
model = User
fields = ('username', 'email', 'groups')
使用方法:
user=User.objects.get(id=1)
s=UserSerializer(user)
接着编写views.py:
class UserListView(generics.ListAPIView):
queryset = user.objects.all()
serializer_class = UserSerializer
from . import views
urlpatterns=[
...
url(r'^list/$',views.UserListView.as_view())
]