Python 使用带有序列化程序的 Django Rest Framework 时出现 AttributeError

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28760356/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 03:42:17  来源:igfitidea点击:

AttributeError while using Django Rest Framework with serializers

pythondjangoserializationdjango-rest-frameworkdjango-1.7

提问by Frankline

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

我正在关注位于此处的使用Django Rest Framework的教程,但我不断收到有关字段的奇怪错误。

I have the following model in my models.py

我有以下模型 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

然后我的序列化器 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.pyas follows:

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

and my urls.py has this line:

我的 urls.py 有这一行:

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:

当我尝试访问时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'.

What I'm I missing?

我错过了什么?

采纳答案by Ashwini Chaudhary

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

many=True从查询集创建序列化程序时简单指定,TaskSerializer(tasks)仅适用于以下的一个实例Task

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

回答by Rodney Hawkins

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)