在django rest中自定义序列化器输出

时间:2014-05-20 07:03:16

标签: python django python-2.7 django-rest-framework

我想自定义序列化程序的输出... 我想在我的序列化程序输出中添加额外的字段..

我的模特:

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)

我的序列化器:

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)

我想要的是在显示MatchupActivity列表中时显示matchup字段。 例如:

目前的反应是这样的..

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

我希望回复是这样的..

{
    "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 个答案:

答案 0 :(得分:1)

为MatchupUser模型编写单独的序列化程序,而不是使用:

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

使用:

matchup = MatchupUserSerializer()

按照指示here