先附上地址:https://www.django-rest-framework.org/
首先呢,需要安装三个依赖包
pip install djangorestframeworkpip install markdown # Markdown support for the browsable API.pip install django-filter # Filtering support
然后再base.py配置app和鉴权
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']}
接着前往urls.py 配置啊吧啊吧
from django.urls import path, includefrom rest_framework import routers, serializers, viewsetsfrom accounts.models import CustomUserfrom jobs.models import Job# Serializers define the API representation.class UserSerializer(serializers.HyperlinkedModelSerializer):class Meta:model = CustomUserfields = ['url', 'username', 'email', 'is_staff']# ViewSets define the view behavior.class UserViewSet(viewsets.ModelViewSet):queryset = CustomUser.objects.all()serializer_class = UserSerializerclass JobSerializer(serializers.HyperlinkedModelSerializer):class Meta:model = Jobfields = '__all__'class JobViewSet(viewsets.ModelViewSet):queryset = Job.objects.all()serializer_class = JobSerializer# Routers provide an easy way of automatically determining the URL conf.router = routers.DefaultRouter()router.register(r'users', UserViewSet)router.register(r'jobs', JobViewSet)urlpatterns = [path('api-auth/', include('rest_framework.urls', namespace='rest_framework')),path('api/', include(router.urls)),]
