【问题标题】:Serializing User model序列化用户模型
【发布时间】:2018-06-28 05:55:45
【问题描述】:

我有以下代码应该返回我网站中注册的所有用户,但由于某种原因,它只返回了我最后一个签名的用户,我需要我的 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

【问题讨论】:

    标签: python json django django-rest-framework


    【解决方案1】:

    这就是你的问题所在:

    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 rest 框架和 APIView,因此您不需要 json.dumps

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

    from rest_framework.response import Response
    

    然后将您的退货声明更改为:

    return Response(dictionary)
    

    【讨论】:

    • 首先,感谢您的回复。会是这样吗? def get(self, request, format=None): users = User.objects.all() response = self.serializer(users, many=True) dictionary = {} for j in range(0,len(response.data) ): dictionary.update(response.data[j]) myresponse = "" for i, (val, v) in enumerate(dictionary.items()): myresponse = [{"text":v} for v 在字典中。 values()] 打印(我的回复)
    • 好的,我将其更新如下: class ProfilesAPI(APIView): serializer = ProfileSerializer def get(self, request, format=None): users = User.objects.all() response = self. serializer(users, many=True) dictionary = {'messages': []} for user in response.data: dictionary[messages].append({'text': user.id}) dictionary[messages].append({ 'text': user.username}) return Response(dictionary) 但它返回一个错误'name 'messages' is not defined'。
    • 您应该在消息周围加上引号,即dictionary['messages']。我已经更新了我的答案
    • 感谢您的帮助。现在它向我抛出这个错误:异常类型:AttributeError 异常值:'collections.OrderedDict'对象没有属性'id'它不起作用,对于用户名或id。
    • 是的,很抱歉。这是一个有序字典而不是我更新我的答案的对象
    猜你喜欢
    • 2013-05-10
    • 1970-01-01
    • 2016-08-08
    • 1970-01-01
    • 1970-01-01
    • 2019-06-02
    • 1970-01-01
    • 2011-04-30
    • 2019-06-20
    相关资源
    最近更新 更多