0

I am new to Django. And I trying to work along with django-rest-framework (DRF from now on) to create an API so I can consume it from a React frontend.

I am getting currently:

AttributeError: Got AttributeError when attempting to get a value for field answers_set on serializer QuestionSerializer.

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

Original exception text was: 'Question' object has no attribute 'answers_set'.

But I have followed this question to add extra fields and this one to dig into that error. Still getting the same error.

So, I have two models:

Question

class Question(models.Model):
    id = models.AutoField(primary_key=True)
    title = models.CharField(max_length=250)
    description = models.CharField(max_length=1000)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=False, auto_now_add=True)

Answer

class Answer(models.Model):
    id = models.AutoField(primary_key=True)
    answer = models.CharField(max_length=1000)
    question = models.ForeignKey(Question, on_delete=models.CASCADE, default=None)
    created_by = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    created_at = models.DateTimeField(auto_now=False, auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=False, auto_now_add=True)

So I have two serializers:

AnswerSerializer

class AnswerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Answer
        fields = ['answer', 'created_by', 'updated_at']

QuestionSerializer

class QuestionSerializer(serializers.ModelSerializer):
    answers_set = AnswerSerializer(many=True)

    class Meta:
        model = Question
        fields = [
            'id',
            'title',
            'description',
            'answers_set',
            'created_by',
            'created_at',
            'updated_at',
        ]

I guess this is the "relevant" information to get what I am doing wrong... So, what am I doing wrong?

Maramal
  • 3,145
  • 9
  • 46
  • 90

1 Answers1

1

It should be answer_set instead of answers_set

OR

set the source as

answers_set = AnswerSerializer(many=True, source="answer_set")
JPG
  • 82,442
  • 19
  • 127
  • 206
  • 1
    I thought `answers_set` was literal depending on the variable name, not a reserved word. Thank you. – Maramal Mar 31 '21 at 01:44