2

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...
    }
}

1 Answer 1

1

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

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

Comments

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.