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

我的模型:

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列表中时显示对战字段。
例:

目前的反应是这样的。

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

最佳答案

为MatchupUser模型编写一个单独的序列化器,而不要使用:

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


使用:

matchup = MatchupUserSerializer()


按照指示here

关于python - 在Django Rest中自定义序列化器输出,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/23753001/

10-11 17:16