我尝试在 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/