Django REST Framework (AttributeError : Got AttributeError when attempting to get a value for field " " on serializer " ")

Question:

Got AttributeError when attempting to get a value for field Firstname in serializer NameSerializer.

The serializer field might be named incorrectly and not match
any attribute or key on the QuerySet instance.

The original exception text was:

'QuerySet' object has no attribute Firstname.

Error:
Error

serializers.py

from rest_framework import serializers
from .models import Name, ForeName

class NameSerializer(serializers.ModelSerializer):
    class Meta:
        model = Name
        fields = '__all__'

class ForeNameSerializer(serializers.ModelSerializer):
    forenames = NameSerializer(many=True, read_only=True)
    class Meta:
        model = ForeName
        fields= '__all__'

models.py

from django.db import models
import uuid

# create your models here
class ForeName(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    Forename = models.CharField(max_length=30)

    def __str__(self):
        return self.Forename

class Name(models.Model):
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    Firstname = models.ForeignKey(ForeName, on_delete=models.PROTECT, 
                    related_name="forenames")

views.py

from rest_framework.decorators import api_view
from rest_framework.response import Response
from .serializers import NameSerializer
from .models import Name

# Create your views here.
@api_view(['GET'])
def names_list(request):
    names = Name.objects.all()
    myname = NameSerializer(names)
    return Response({"restult": { 
        "Forename" : myname.data,
        }
Asked By: Stephen

||

Answers:

You need to add many=True in your serializer when initializing with multiple instances.

myname = NameSerializer(names,many=True)

Answered By: Rohit Rahman

Firstly, field names should be all lowercase, using underscores instead of camelCase, according to the official document. It’s a convention that we all should follow. ex – first_name and fore_name

And as per your question, you should write
myname = NameSerializer(names, many=True)
in views.py, because you’re trying to serialize multiple objects.

Answered By: Kashish-2001