LoginSignup
1
1

More than 3 years have passed since last update.

【Django】TypeError: Object of type QuerySet is not JSON serializable

Last updated at Posted at 2019-09-08

はじめに

以下のようにBlogモデルへの検索結果をそのままJsonResponseで返却しようとしたところ、表題のようなエラーが出た。エラー内容は「検索結果がQuerySetだとJSON形式に変換できないよ」というもの。
このエラーへの対処方法を備忘録として残しておく。

views.py
blog_list = Blog.objects.filter(user=request.user)
ret = { "blog_list": blog_list }
return JsonResponse(ret)

対処方法

serializersを用いてjson型に変換する。

views.py
from django.core import serializers
...
blog_list = serializers.serialize("json", Blog.objects.filter(user=request.user))
ret = { "blog_list": blog_list }
return JsonResponse(ret)

おわりに

以下を参考。
https://stackoverflow.com/questions/41992889/queryset-is-not-json-serializable-django/41992944

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1