Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Got AttributeError when attempting to get a value for field on serializer

I get the following error:

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

Why do I get an error?

This is my 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)

This is my serializers.py:

from rest_framework import serializers
from .models import Athlete

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

This is my 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)
like image 375
user1283776 Avatar asked Nov 04 '15 13:11

user1283776


Video Answer


1 Answers

try this:

serializer = AthleteSerializer(all_athletes, many=True)
like image 110
Hasan Ramezani Avatar answered Oct 12 '22 08:10

Hasan Ramezani