在Django res中自定义序列化程序输出

2024-10-01 07:30:09 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我的型号:

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)

我的序列化程序:

^{pr2}$

我想要的是在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...
    }
}

Tags: answerself程序localhosthttp序列化timemodels
1条回答
网友
1楼 · 发布于 2024-10-01 07:30:09

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

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

使用:

^{pr2}$

按指示here

相关问题 更多 >