Pradeep Agnihotri
Pradeep Agnihotri

Reputation: 371

customize serializer output in django rest

i want to customize output of serializer ... i want to add extra field to my serializer output..

my model:

class MatchupActivity(models.Model):
    matchup_user = models.ForeignKey(MatchupUser)
    question = models.ForeignKey(Question)
    answer = models.ForeignKey(Answer)
    points = models.PositiveIntegerField()
    time = models.PositiveIntegerField() # in seconds

    def __unicode__(self):
        return u"%d - [%s]" % (self.id, self.matchup_user)

my serializer:

class MatchupActivitySerializer(serializers.Serializer):
    """
    """

    url = serializers.HyperlinkedIdentityField(view_name='matchupactivity-detail')
    question = serializers.HyperlinkedRelatedField(queryset=Question.objects.all(), view_name='question-detail')
    answer = serializers.HyperlinkedRelatedField(queryset=Answer.objects.all(), view_name='answer-detail')
    points = serializers.IntegerField(required=True)
    time = serializers.IntegerField(required=True)
    matchup = serializers.HyperlinkedRelatedField(queryset=Matchup.objects.all(), view_name='matchup-detail')

    def to_native(self, obj):
        if 'matchup' in self.fields:
            self.fields.pop('matchup')
        return super(MatchupActivitySerializer, self).to_native(obj)

    def restore_object(self, attrs, instance=None):
        request = self.context.get('request')
        field = serializers.HyperlinkedRelatedField(queryset=Matchup.objects.all(), view_name='matchup-detail')
        matchup = self.init_data['matchup']
        matchup_user = MatchupUser.objects.get(matchup=field.from_native(matchup), user=request.user)
        attrs['matchup_user'] = matchup_user
        attrs.pop('matchup')      
        return MatchupActivity(**attrs)

what i want is to show matchup field when a in a list of MatchupActivity is shown. Example:

currently response is like this..

{
    "url": "http://localhost:8000/matchup-activities/1/", 
    "question": "http://localhost:8000/questions/1/", 
    "answer": "http://localhost:8000/answers/1/", 
    "points": 1, 
    "time": 1
}

i want response is like this..

{
    "url": "http://localhost:8000/matchup-activities/1/", 
    "question": "http://localhost:8000/questions/1/", 
    "answer": "http://localhost:8000/answers/1/", 
    "points": 1, 
    "time": 1,
    "matchup":{
        #matchup related fields...
    }
}

Upvotes: 2

Views: 1907

Answers (1)

prsnca
prsnca

Reputation: 236

Write a separate serializer for the MatchupUser model, and instead of using:

matchup = serializers.HyperlinkedRelatedField(queryset=Matchup.objects.all(), view_name='matchup-detail')

Use:

matchup = MatchupUserSerializer()

As instructed here

Upvotes: 1

Related Questions