AttributeError while using Django Rest Framework with serializers

▼魔方 西西 提交于 2019-12-03 01:08:30

Simple specify many=True when creating a serializer from queryset, TaskSerializer(tasks) will work only with one instance of Task:

tasks = Task.objects.all()
serializer = TaskSerializer(tasks, many=True)

The problem here is that you are trying to convert a Queryset(list) of entries into a single entry. The solution is something along these lines.

from rest_framework import serializers

class TaskListSerializer(serializers.ListSerializer):
    child = TaskSerializer()
    allow_null = True
    many = True

Then

if request.method == 'GET':
        tasks = Task.objects.all()
        serializer = TaskListSerializer(tasks)
        return Response(serializer.data)
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!