python - 在django中将序列化数据转换为字典

标签 python django

我尝试在 Django 中序列化用户数据,但后来我想将其作为字典打印在控制台中,它给了我一个空字典,我该如何处理。

序列化器.py

from rest_framework import routers, serializers, viewsets
from accounts.models import User



class UserSerializer(serializers.ModelSerializer):
    class Meta:
        model = User
        fields = 'username', 'email', 'first_name', 'last_name', 'date_joined'

View .py

from django.shortcuts import render
from rest_framework.generics import  ListAPIView
from rest_framework.response import Response
from .serialize import UserSerializer




import json



class userApi(ListAPIView):
    def get(self, request):
        queryset = User.objects.all()
        serializer_class = UserSerializer(queryset, many=True)
        return Response(serializer_class.data)

apiuser=userApi()
point = json.dumps(apiuser.__dict__)


print(point)

控制台

Watching for file changes with StatReloader
[2020-11-02 15:45:50,086] autoreload: INFO - Watching for file changes with StatReloader
Performing system checks...

**{}**#This is what it is printing

大家帮忙

最佳答案

Serializers默认返回字典,所以如果要在控制台打印序列化后的数据,必须在view的get方法中打印。像这样:

class userApi(ListAPIView):
    def get(self, request):
        queryset = User.objects.all()
        serializer_class = UserSerializer(queryset, many=True)
        print(serializer_class.data)
        return Response(serializer_class.data)

然后像这样为 View 设置一个 url:

path('users/', userApi.as_view())

当您在浏览器中打开此 url 或向其发送 get 请求时,序列化数据将打印在控制台中。

关于python - 在django中将序列化数据转换为字典,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64646178/

相关文章:

python - 如何更优雅地构造一个 2 的幂数的 numpy 数组?

python - 在 Python 2.7 中使用 Unicode 转义时出现奇怪的问题

python - TF Hub微调错误: ValueError: Failed to find data adapter that can handle input

python - Django 模型名称不区分大小写,对吗?

Python 正则表达式匹配或潜在匹配

python - 如何使用 tensorflow 2.0 计算中位数?

python-3.x - 包含 GeoPoint 的位置列表 - (geo_spatial_filter_fields, geo_distance)

python - 错误 324 空响应 - AttributeError : 'NoneType' object has no attribute 'select'

python - 创建一个可调用函数来生成 django 模型中的属性值

Django 自动完成灯 - "The results could not be loaded"