gpt4 book ai didi

Django休息框架: Do not return array but list of objects with id as key

转载 作者:行者123 更新时间:2023-12-02 09:51:35 27 4
gpt4 key购买 nike

Django Rest 框架在 API 端点返回以下输出

  [
{
"id": "QFELD_2.3.2.QF1",
"siteuxid": "VBKM02_Abschlusstest",
"section": 2,
"maxpoints": 4,
"intest": true,
"uxid": "KA0",
"points": 0,
"value": 0,
"rawinput": "",
"state": 3
},
{
"id": "QFELD_2.3.2.QF2",
"siteuxid": "VBKM02_Abschlusstest",
"section": 2,
"maxpoints": 4,
"intest": true,
"uxid": "KA1",
"points": 0,
"value": 0,
"rawinput": "",
"state": 3
},
...

是否可以以列表对象格式返回数据,例如:

  {
"QFELD_2.3.2.QF1" : {
"siteuxid": "VBKM02",
"section": 2,
"maxpoints": 4,
"intest": true,
"uxid": "KA0",
"points": 0,
"value": 0,
"rawinput": "",
"state": 3
},
"QFELD_2.3.2.QF2" : {
"siteuxid": "VBKM02",
"section": 2,
"maxpoints": 4,
"intest": true,
"uxid": "KA1",
"points": 0,
"value": 0,
"rawinput": "",
"state": 3
},
...

我的序列化器是:

class ScoreSerializer(serializers.ModelSerializer):
id = serializers.CharField(required=False, allow_blank=True, max_length=100, source='q_id')
class Meta:
model = Score
fields = ('id', 'siteuxid', 'section', 'maxpoints', 'intest', 'uxid', 'points', 'value', 'rawinput', 'state')

View 是:

class ScoreViewSet(viewsets.ModelViewSet):

serializer_class = ScoreSerializer

最佳答案

ListMixin代码 a 是一个很好的起点。您应该获取序列化器的结果并根据需要对其进行转换。

class ListModelMixin(object):
"""
List a queryset.
"""
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())

page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(page, many=True)
# Might need to change this not to transform all the data
data = {i['id']: i for i in serializer.data}
return self.get_paginated_response(data)

serializer = self.get_serializer(queryset, many=True)
data = {i['id']: i for i in serializer.data}
return Response(data)

关于Django休息框架: Do not return array but list of objects with id as key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39878078/

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