我正在关注位于使用here的Django 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'.
我错过了什么?
答案 0 :(得分:67)
从查询集创建序列化程序时,只需指定many=True
,TaskSerializer(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)