序列化用户模型

时间:2018-01-19 03:02:44

标签: python json django django-rest-framework

我有以下代码应该返回我在我的网站中注册的所有用户,但由于某种原因它只是返回给我最后签名的用户,我需要我的JSON中的所有用户。

from django.shortcuts import render, redirect
import json
from django.http import HttpResponse
from rest_framework.response import Response
from rest_framework.views import APIView
from profiles.serializers import ProfileSerializer
from django.contrib.auth.models import User
from rest_framework.decorators import api_view


class ProfilesAPI(APIView):
serializer = ProfileSerializer

def get(self, request, format=None):
    users = User.objects.all()
    response = self.serializer(users, many=True)
    for j in range(0,len(response.data)):
     dictionary = response.data[j]
     myresponse = ""


    for i, (val, v) in enumerate(dictionary.items()):
         myresponse = [{"text":v} for v in dictionary.values()]
         print(myresponse)


    return HttpResponse(json.dumps({'messages': myresponse}), content_type='application/json')

然后把我扔了,即使我注册了多个用户。

My JSON

1 个答案:

答案 0 :(得分:0)

这就是你的问题所在:

dictionary = response.data[j]

您声明字典,同时声明循环中具有最新值的现有值。当循环退出时,字典将只包含一个结果(循环中的最后一个)

你应该在循环之外声明它,然后调用dict.update这样的东西:

dictionary = {}

for j in range(0,len(response.data)):
    dictionary.update(response.data[j])

这解决了你的问题。

但是生成这个新词典没有意义。如果您需要自定义响应,则可以在response.data上迭代一次。

由于response.data是用户列表,您可以执行此操作

dictionary = {'messages': []}

for user in response.data:
    dictionary['messages'].append({'text': user['id']})
    dictionary['messages'].append({'text': user['username']})

此外,由于您使用的是django休息框架和APIView,因此您不需要json.dumps

django框架有一个Response类来处理它,它还设置了适当的标题。

from rest_framework.response import Response

然后将return语句更改为:

return Response(dictionary)
相关问题