Django rest framework官方文档示例(二)
一、一个纯python的api
1.1、polls下的urls.py
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from .models import Poll
def polls_list(request):
MAX_OBJECTS = 20
polls = Poll.objects.all()[:MAX_OBJECTS]
data = {"results": list(polls.values("question", "created_by__username", "pub_date"))}
return JsonResponse(data)
def polls_detail(request, pk):
poll = get_object_or_404(Poll, pk=pk)
data = {"results": {
"question": poll.question,
"created_by": poll.created_by.username,
"pub_date": poll.pub_date
}}
return JsonResponse(data)
1.2、polls下的views.py
from django.shortcuts import render, get_object_or_404
from django.http import JsonResponse
from .models import Poll
def polls_list(request):
# 将获取20个数据
MAX_OBJECTS = 20
polls = Poll.objects.all()[:MAX_OBJECTS]
data = {"results": list(polls.values("question", "created_by__username", "pub_date"))}
return JsonResponse(data)
def polls_detail(request, pk):
poll = get_object_or_404(Poll, pk=pk)
data = {"results": {
"question": poll.question,
"created_by": poll.created_by.username,
"pub_date": poll.pub_date
}}
return JsonResponse(data)
A JsonResponse is a like HttpResponse with content-type=application/json.
1.3、测试api
polls_list:
polls_detail:
1.4、为什么需要DRF?
We were able to build the API with just Django, without using DRF, so why do we need DRF? Almost always, you
will need common tasks with your APIs, such as access control, serialization, rate limiting and more.
DRF provides a well thought out set of base components and convenient hook points for building APIs. We will be
using DRF in the rest of the chapters.