'Django rest framework serializer Got AttributeError when attempting to get a value for field `field` on serializer. Try to nest serializers

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

Model

class VestingChoice(models.Model):
id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
participant = ForeignKey('Participant', on_delete=CASCADE, related_name="participants_id")
vesting = ForeignKey('Vesting', on_delete=CASCADE, related_name="vestings")


class VestingLocationRate(models.Model):
id = UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
vesting_choice_id = ForeignKey('VestingChoice', on_delete=CASCADE, 
related_name="vesting_choice")
country_id = ForeignKey(Country, on_delete=CASCADE, related_name="country_id")

Serializers

class VestingChoiceSerializer(serializers.ModelSerializer):

class Meta:
    model = VestingChoice
    fields = "__all__"

class VestingLocationRateSerializer(serializers.ModelSerializer):
vesting_choice_id = VestingChoiceSerializer(many = False)
country_id = CountrySerializer(many = False)

class Meta: 
    model = VestingLocationRate
    fields = "__all__"


Solution 1:[1]

  • In vesting_choice_id on_delete=models.CASCADE not on_delete=CASCADE
  • And seems like you haven't migrate after adding vesting_choice_id, so try to run python manage.py makemigrations then python manage.py migrate

Solution 2:[2]

If you're trying to fetch multiple instances of your model, make sure that in your view function, at the serialization level, you have set many to True

Something like this

models = YourModel.objects.all()
serializer = YourModelSerializer(models, many=True)
return JsonResponse(serializer.data, safe=False)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Adil Mohak
Solution 2 Amrou