[Django]-How to define models/serializers correctly for Django REST Framework?

2๐Ÿ‘

โœ…

The urls come because you inherit HyperlinkedModelSerializer.

class QuestionSerializer(serializers.HyperlinkedModelSerializer):
    ...

If you donโ€™t want them, use a different base class โ€“ perhaps just a ModelSerializer.

๐Ÿ‘คwim

2๐Ÿ‘

I believe this will work.

class AnswerSerializer(serializers.ModelSerializer):
    class Meta:
        model = Answer
        fields = ('answerid', 'text')

class QuestionSerializer(serializers.ModelSerializer):

answer = AnswerSerializer(source="answers) 
class Meta:
    model = Question
    fields = ('question', 'answer', 'correct')
    read_only_fields = ('answer',)
    depth = 1

You may need to change the source to correctly get the answers you need.

The serializers.HyperlinkedModelSerializer will automatically insert the url field in your response.

๐Ÿ‘คjarussi

Leave a comment