0

I have nested models and many to many relations. When I try to serialize them, results are not visible.

Tried everything in documentation and related names etc.

My base model is like this:

class Question(models.Model):
    ques_code = models.CharField(max_length=12, null=True, default='Ques Code')

    def __str__(self):
        return self.ques_code

Child Model is:

class MCQuestion(Question):
    answer_order = models.CharField(
        max_length=30, null=True, blank=True,
        choices=ANSWER_ORDER_OPTIONS,
        help_text=_("The order in which multichoice "
                    "answer options are displayed "
                    "to the user"),
        verbose_name=_("Answer Order"))

Then linked answer class with key as:

class Answer(models.Model):
    mcquestion = models.ForeignKey(MCQuestion,related_name='answers', on_delete=models.CASCADE)

    content = models.CharField(max_length=1000,
                               blank=False,
                               help_text=_("Enter the answer text that "
                                           "you want displayed"),
                               verbose_name=_("Content"))

    correct = models.BooleanField(blank=False,
                                  default=False,
                                  help_text=_("Is this a correct answer?"),
                                  verbose_name=_("Correct"))

    def __str__(self):
        return self.content

Serializers are as:

class AnswerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Answer
        fields = ('content','correct')


class MCQuestionSerializer(serializers.ModelSerializer):
    answers = AnswerSerializer(many=True, read_only=True)
    #answers = serializers.SerializerMethodField()
    quiz = QuizSerializer(many=True)

    class Meta:
        model = MCQuestion
        fields = ('ques_code','answers')

Views are:

class QuestionViewSet(viewsets.ModelViewSet):
    queryset = Question.objects.all()
    serializer_class = MCQuestionSerializer

When I access API for questions, nested answers are not visible. I checked all documentation and checked and changed my code.

If I try using answers = serializers.SerializerMethodField() and define get_answers function for it, error comes saying "Question has no attribute of answers"

I think it is due to child and mother model system. It is searching attribute in Question, not in MCQuestion model. What can I do?

1 Answer 1

1

You were using the "wrong queryset-serializer combination" for the viewset class.

So, change the queryset reference in your view class as ,

class QuestionViewSet(viewsets.ModelViewSet):
    queryset = MCQuestion.objects.all()
    serializer_class = MCQuestionSerializer

Apart from that, I'm not sure you are aware of Django Model Inheritance. Anyway read it from here if necessary, Django Model Inheriitance

Sign up to request clarification or add additional context in comments.

5 Comments

This gave me this error: django.db.utils.OperationalError: (1054, "Unknown column 'multichoice_answer.mcquestion_id' in 'field list'")
Did you migrated the db?
Yes , let me check code more if I am missing anything .. I have not included id anywhere in fields
The erros seems like you forgot to do the db migration
Got it ... done. Thanks. Works now. I changed the model .. migration doesn't work on existing data..

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.