将Django Rest Framework与序列化程序一起使用时的AttributeError

时间:2015-02-27 08:17:24

标签: python django serialization django-rest-framework django-1.7

我正在关注位于使用hereDjango Rest Framework的教程,并且我不断收到有关字段的奇怪错误。

我的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()

然后我的serializers.py

中的序列化程序
from rest_framework import serializers

from task.models import Task

class TaskSerializer(serializers.ModelSerializer):

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

和我的views.py如下:

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
                )

我的urls.py有这一行:

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

当我尝试访问curl http://localhost:9000/api/tasks/时,我不断收到以下错误,我不知道该怎么做:

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'.

我错过了什么?

2 个答案:

答案 0 :(得分:67)

从查询集创建序列化程序时,只需指定many=TrueTaskSerializer(tasks)仅适用于Task的一个实例:

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

答案 1 :(得分:4)

这里的问题是您正在尝试将条目的Queryset(列表)转换为单个条目。解决方案就是这样的。

from rest_framework import serializers

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

然后

if request.method == 'GET':
        tasks = Task.objects.all()
        serializer = TaskListSerializer(tasks)
        return Response(serializer.data)