回顾DRF框架时,产生疑惑点
代码如下:
class BooksAPIVIew(View):
def get(self, request):
"""
查询所有图书
路由:GET /books/
"""
queryset = BookInfo.objects.all()
book_list = []
for book in queryset:
book_list.append({
'id': book.id,
'btitle': book.btitle,
'bpub_date': book.bpub_date,
'bread': book.bread,
'bcomment': book.bcomment,
'image': book.image.url if book.image else ''
})
return JsonResponse(book_list, safe=False)
问题点:
return JsonResponse(book_list,safe=False),其中safe=False是做什么用,联想到类似于过滤器中的safe防转译…
解决问题 >>>
类似于此种问题,直接进去JsonResponse源码里面找答案,是最有效的方法,
def __init__(self, data, encoder=DjangoJSONEncoder, safe=True,
json_dumps_params=None, **kwargs):
if safe and not isinstance(data, dict):
raise TypeError(
'In order to allow non-dict objects to be serialized set the '
'safe parameter to False.'
)
if json_dumps_params is None:
json_dumps_params = {}
kwargs.setdefault('content_type', 'application/json')
data = json.dumps(data, cls=encoder, **json_dumps_params)
super(JsonResponse, self).__init__(content=data, **kwargs)
其中:
if safe and not isinstance(data,dict):
raise TypeError(
'In order to allow non-dict objects to be serialized 'safe parameter to False'
)
告诉我们,当safe=True并且所传过来的data不是dict类型时,会引发异常,提醒我们如果传过来的objects不是dict,就将safe参数设置为False.
其实这也告诉了我们一点,标准的JsonResponse内的数据类型应该为dict字典类型,而不该是其他类型。
如有说得不对,还请点醒我 傲娇脸哈哈哈