0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

[Django][RestFramework]Object of type "AA" is not JSON serializable エラー

Posted at

生のSQL文を実行したいと考え模索していたが、今回のエラーが解決できたので備忘録として残す。

##エラー内容
Object of type "AA" is not JSON serializable
とエラーが出た 
AAはJson形式ではないという内容

##解決

views.py
from .models import BaseAPI
from .serializer import BaseAPISerializer
from rest_framework import generics
from rest_framework.views import APIView
from rest_framework.response import Response


class BaseAPIViewSet_GET(APIView):
    def get(self, request, pk, format=None):
        sql = "SQL文"
        queryset = BaseAPI.objects.raw(sql,pk)
        return Response(queryset.query) #ここが解決ポイント
urls.py
path('user/<int:pk>/test', BaseAPIViewSet_GET.as_view(), name='GET'),

ちなみにSQL文について
変数を使用した複数行に渡ってSQL文を書きたいと考えていた時があったが、

SELECT * FROM api WHERE name1=(SELECT name2 FROM api WHERE id=%s)
views.py
queryset = BaseAPI.objects.raw(sql,[pk]) #ここで実行

SELECTの中にSELECTを書くことが可能なため、一行のSQL文で自在に操作が可能

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?