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.

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值