gpt4 book ai didi

django - 如何在 Django REST Framework 中返回自定义 JSON 输出

转载 作者:行者123 更新时间:2023-12-04 11:02:30 25 4
gpt4 key购买 nike

我正在尝试返回具有以下结构的自定义 json

[ { 
'yesterday': [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}],

'today': [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}],

'tomorrow': [{'teams': "team a -team b", 'start_time': "0: 11", 'pick': "X2", 'score': "1:4", 'odds': 1.25, 'won_or_lost': "won", 'date': "2019-01-8"}]
}]

以下是我的代码:

序列化程序.py
class GamesSerializer(serializers.Serializer):
class Meta:
model = AllGames
fields = ('teams', 'start_time', 'pick',
'score', 'odds', 'won_or_lost', 'date')


class GamesViewSet(viewsets.ModelViewSet):
today_date = date_picker

yesterday = AllGames.objects.filter(
date=today_date(-1)).order_by('start_time', 'teams')
today = AllGames.objects.filter(
date=today_date(0)).order_by('start_time', 'teams')
tomorrow = AllGames.objects.filter(
date=today_date(1)).order_by('start_time', 'teams')

queryset = [yesterday, today, tomorrow]
serializer_class = GamesSerializer

电流输出
[
{},
{},
{}
]

如何修改我的 GamesSerializer 返回如上所示的自定义输出。

最佳答案

您可以从 DRF ModelViewSet 转换您的响应类至 ViewSet .
然后你可以在返回响应之前进一步解析你的数据,通过覆盖 retrieve
如此处所述:https://www.django-rest-framework.org/api-guide/viewsets/#example

关于django - 如何在 Django REST Framework 中返回自定义 JSON 输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58711832/

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