AttributeError while using Django Rest Framework w

2019-03-17 08:40发布

问题:

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

from django.db import models

class Task(models.Model):
    completed = models.BooleanField(default=False)
    title = models.CharField(max_length=100)
    description = models.TextField()

Then my serializer in serializers.py

from rest_framework import serializers

from task.models import Task

class TaskSerializer(serializers.ModelSerializer):

    class Meta:
        model = Task
        fields = ('title', 'description', 'completed')

and my views.py as follows:

from rest_framework import status
from rest_framework.decorators import api_view
from rest_framework.response import Response

from task.models import Task
from api.serializers import TaskSerializer


    @api_view(['GET', 'POST'])
    def task_list(request):
        """
        List all tasks, or create a new task
        """
        if request.method == 'GET':
            tasks = Task.objects.all()
            serializer = TaskSerializer(tasks)
            return Response(serializer.data)

        elif request.method == 'POST':
            serializer = TaskSerializer(data=request.DATA)
            if serializer.is_valid():
                serializer.save()
                return Response(serializer.data, status=status.HTTP_201_CREATED)
            else:
                return Response(
                    serializer.errors, status=status.HTTP_400_BAD_REQUEST
                )

and my urls.py has this line:

url(r'^tasks/$', 'task_list', name='task_list'),

When I try accessing curl http://localhost:9000/api/tasks/, I keep getting the following error and I'm not sure what to make of it:

AttributeError at /api/tasks/
Got AttributeError when attempting to get a value for field `title` on serializer `TaskSerializer`.
The serializer field might be named incorrectly and not match any attribute or key on the `QuerySet` instance.
Original exception text was: 'QuerySet' object has no attribute 'title'.

What I'm I missing?

回答1:

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)


回答2:

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)