AttributeError while using Django Rest Framework with serializers

前端 未结 2 510
长情又很酷
长情又很酷 2021-02-02 07:36

I am following a tutorial located here that uses Django Rest Framework, and I keep getting a weird error about a field.

I have the following model in my models.py<

2条回答
  •  無奈伤痛
    2021-02-02 08:06

    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)
    

提交回复
热议问题