## 环境依赖 pip install djangorestframework pip install markdown # Markdown support for the browsable API. pip install django-filter # Filtering support
## 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 = [ ... path('api-auth/', include('rest_framework.urls')) # Note that the URL path can be whatever you want. ]
## 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' ] }
## 添加路由 from django.urls import path, 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 = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')) ]
from booktest.serializers import BookInfoSerializer, HeroInfoSerializer from booktest.models import BookInfo, HeroInfo book = BookInfo.objects.get(id=1) s = BookInfoSerializer1(instance=book, many=False) s.data
books = BookInfo.objects.all() s = BookInfoSerializer1(instance=books, many=True) s.data
序列化器中的字段个数可以与模型的属性个数不同
可以添加不存在的,也可以不写,但是不能修改
创建序列化器有两个参数BookInfoSerializer(instance, data)
S = BookInfoSerializer(instance=book, many=true) 只做序列化, S.data 可以取值