这是Django在前端(JSON对象数组)进行axios api调用时的响应。
[
{
"id": 1,
"title": "How to create a django-react app",
"body": "You should first do this stuff and that"
},
{
"id": 5,
"title": "How to connect django with react",
"body": "Get this and that stuff"
}
]
但这是我想要的响应(JSON对象的JSON对象)。
Python字典与Javascript对象或Hashmap一样吗?
我可以使用某种中间件来转换形状吗?
serializers.py
需要完成这项工作还是views.py
?如何将响应从对象数组更改为一个或多个对象?
{
1: {
"id": 1,
"title": "How to create a django-react app",
"body": "You should first do this stuff and that"
},
5: {
"id": 5,
"title": "How to connect django with react",
"body": "Get this and that stuff"
}
}
serializers.py
class ArticleSerializer(serializers.ModelSerializer):
class Meta:
model = Article
fields = '__all__'
views.py
class ArticleViewSet(ViewSet):
queryset = Article.objects.all()
def list(self, request):
serializer = ArticleSerializer(ArticleViewSet.queryset, many=True)
return Response(serializer.data)
def retrieve(self, request, pk=None):
article = get_object_or_404(ArticleViewSet.queryset, pk=pk)
serializer = ArticleSerializer(article, many=False)
return Response(serializer.data)
答案 0 :(得分:2)
您应该能够使用ArticleViewSet
的{{1}}方法来构建字典:
list