gpt4 book ai didi

django - 尝试获取序列化器上字段的值时出现AttributeError

转载 作者:行者123 更新时间:2023-12-03 16:29:56 24 4
gpt4 key购买 nike

我收到以下错误

Got AttributeError when attempting to get a value for field first_name on serializer AthleteSerializer. 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 'first_name'.



为什么会出现错误?

这是我的views.py:
from rest_framework.response import Response
from rest_framework.views import APIView
from .models import Athlete

from athletics.serializers import AthleteSerializer

class ListAthletes(APIView):
def get(self, request, format=None):
all_athletes = Athlete.objects.all()
import pdb; pdb.set_trace()
serializer = AthleteSerializer(all_athletes)
return Response(serializer.data)

这是我的serializers.py
from rest_framework import serializers
from .models import Athlete

class AthleteSerializer(serializers.ModelSerializer):
class Meta:
model = Athlete
fields = (
'first_name',
'last_name'
)

这是我的models.py:
from django.db import models

class Athlete(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=30)

最佳答案

试试这个:

serializer = AthleteSerializer(all_athletes, many=True)

关于django - 尝试获取序列化器上字段的值时出现AttributeError,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33523458/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com