gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 06:03:00 25 4
gpt4 key购买 nike

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

我的模型:

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 列表中的 a 时显示匹配字段。示例:

目前的响应是这样的..

{
"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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com