TypeError:“用户”类型的对象不可JSON序列化

时间:2019-05-20 05:00:50

标签: django python-3.x django-rest-framework

如何在Django Rest Framework中返回对象列表。我正在调用一个返回对象列表的函数。

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

class MyView(APIView):
    from .serializers import MySerializer
    from app.permissions import MyPermissionClass
    from .models import MyModel

    serializer_class = MySerializer
    queryset = MyModel.objects.all()
    permission_classes = (MyPermissionClass,)
    pagination_class = None

    def get(self, request, *args, **kwargs):
        data=myfunction(a,b,c)
        # data={list}<class 'list'>: [<User: Negiiii | negiiii>, <User: Negiiii | negiiii>]
        data=json.dumps(data)
        return Response({"data":data})

我需要的结果

[
  {
    "name":"Negi",
    "rollno":14
   },
  {
    "name":"Negi",
    "rollno":13
  }
]

1 个答案:

答案 0 :(得分:3)

您可以使用DRF序列化器序列化数据。 首先,您需要将序列化器类定义为

# serializers.py
from rest_framework import serializers


class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserModel
        fields = ('name', 'rollno')

,然后在视图中使用 UserSerializer

def get(self, request, *args, **kwargs):
    data = myfunction(a, b, c)
    response_data = UserSerializer(data, many=True)
    return Response({"data": response_data.data})