app1/serializers.py 中添加
from rest_framework import serializers
class UserSerializer(serializers.Serializer):
username = serializers.CharField(max_length=20)
first_name = serializers.CharField(max_length=20)
pass
app1/views.py 添加
from django.contrib.auth.models import User
from django.shortcuts import get_object_or_404
from app1.serializers import UserSerializer
from rest_framework import viewsets
from rest_framework.response import Response
class UserViewSet(viewsets.ViewSet):
def list(self, request):
queryset = User.objects.all()
serializer = UserSerializer(queryset, many=True)
return Response(serializer.data)
def retrieve(self, request):
queryset = User.objects.all()
id=request.query_params["id"]
user = get_object_or_404(queryset, id=id)
serializer = UserSerializer(user)
return Response(serializer.data)
app1/urls.py 修改
from django.contrib import admin
from django.urls import path
from app1.views import hello, UserViewSet
urlpatterns = [
path('app1/', hello),
path('user_list', UserViewSet.as_view({'get': 'list'})),
path('user_detail', UserViewSet.as_view({'get': 'retrieve'}))
]
diango1/settings.py 中添加
INSTALLED_APPS = [
...
'rest_framework',
'app1'
]
python manage.py runserver 0.0.0.0:8000
瀏覽器請求
http://127.0.0.1:8000/app1/user_list