Django和DRF的View层获取JSON的方式

调用方法

都是导入urls.py的urlpatterns里配置使用:

path(r'goods/', GoodsListView.as_view(), name="goods-list"),

Django方式

创建一个views_base.py,里面:

# encoding: utf-8
from goods.models import Goods

# Django cpv方式最底层的view
from django.views.generic.base import View

class GoodsListView(View): def get(self, request): """ 通过django的view实现商品列表页 """ json_list = [] goods = Goods.objects.all()[:10] # for good in goods: # json_dict = {} # json_dict["name"] = good.name # json_dict["category"] = good.category.name # json_dict["market_price"] = good.market_price # json_dict["add_time"] = good.add_time # json_list.append(json_dict) # from django.http import HttpResponse # import json # return HttpResponse(json.dumps(json_list),content_type="application/json") from django.forms.models import model_to_dict for good in goods: json_dict = model_to_dict(good) json_list.append(json_dict) import json from django.core import serializers json_data = serializers.serialize('json', goods) json_data = json.loads(json_data) from django.http import HttpResponse, JsonResponse # jsonResponse做的工作也就是加上了dumps和content_type # return HttpResponse(json.dumps(json_data), content_type="application/json") # 注释掉loads,下面语句正常 # return HttpResponse(json_data, content_type="application/json") # 返回的不为dict时要设置safe=False return JsonResponse(json_data, safe=False)

DRF方式

自定义model的序列化器,在serializers.py:

from rest_framework import serializers


class GoodsSerializer(serializers.Serializer):
    def update(self, instance, validated_data):
        pass

    def create(self, validated_data):
        pass

    name = serializers.CharField(required=True, max_length=100)
    click_num = serializers.IntegerField(default=0)

在views.py:

from rest_framework.views import APIView
from rest_framework.response import Response

from .serializers import GoodsSerializer
from .models import Goods


class GoodsListView(APIView):
    def get(self, response, format=None):
        goods = Goods.objects.all()[:10]
        goods_serializer = GoodsSerializer(goods, many=True)
        return Response(goods_serializer.data)

 

其中DRF方式更强大,在浏览器请求下会直接返回一个易读的HTML而不是JSON。可以用Postman再试试。

转载于:https://www.cnblogs.com/LiuZhiHao/p/10273480.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值