出现错误:用户类型的对象在Django Python中无法JSON序列化 [英] Getting error : Object of type User is not JSON serializable in django python

查看:101
本文介绍了出现错误:用户类型的对象在Django Python中无法JSON序列化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Django python中是新来的,当我尝试从3个表中获取数据时,我得到了错误 User类型的对象不是JSON可序列化的,有人可以帮助我吗,为什么收到此错误?在这里,我添加了我的 views.py models.py 文件

i am new here in django python, when i am trying to get data, from 3 tables, i am getting error Object of type User is not JSON serializable, can anyone please help me why i am getting this error ? here i have added my views.py and models.py file

views.py

# views.py
from tokenize import Token

from django.contrib.auth import authenticate
from rest_framework import status
from rest_framework.exceptions import ValidationError
from rest_framework.status import HTTP_400_BAD_REQUEST, HTTP_200_OK
from rest_framework.views import APIView
from rest_framework.response import Response
from django.conf import settings
from rest_framework.permissions import AllowAny
from django.contrib.auth.models import User
from django.contrib.auth.hashers import make_password
from django.core.exceptions import ValidationError
from django.core.validators import validate_email
from . import utils
import jwt
import json

from trialrisk.models import UserProfile, Company, InviteUser


class UserProfile(APIView):

    def post(self, request):
        try:
                data = request.data
                user_id = data['user_id']

                user_data = User.objects.all().select_related('user_profile').select_related('company')

                return Response({"success": True, "status": "Success", "data": user_data},
                                status=status.HTTP_201_CREATED)

        except Exception as exp:
            print("Unexpected exception occurred: " + str(exp))
            return Response({"success": False, "error": "Unexpected error occurred, please report this to Admin"},
                            status=status.HTTP_500_INTERNAL_SERVER_ERROR)

models.py

models.py

class UserProfile(models.Model):

    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_profile")
    usertype = models.SmallIntegerField()
    title = models.CharField(max_length=255, null=True)
    dob = models.CharField(max_length=255, null=True)
    address = models.CharField(max_length=255, null=True)
    country = models.CharField(max_length=255, null=True)
    city = models.CharField(max_length=255, null=True)
    zip = models.CharField(max_length=255, null=True)
    photo = models.CharField(max_length=255, null=True)

    def __str__(self):
        return "{} - {}".format(self.title, self.dob, self.address, self.country, self.city, self.zip, self.photo,
                                self.user,self.usertype)

class Company(models.Model) :

    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="company")
    name = models.CharField(max_length=255, null=True)
    address = models.CharField(max_length=255, null=True)
    zip = models.CharField(max_length=255, null=True)
    phone = models.CharField(max_length=255, null=True)

    def __str__(self):
        return "{} - {}".format(self.name, self.address,self.phone, self.zip)

class InviteUser(models.Model):

    user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="invite_user")
    email = models.CharField(max_length=255,null=False)

    def __set__(self):
        return "{} - {}".format(self.user, self.email)

推荐答案

不可能将Django模型对象作为数据返回.为此,您应该使用序列化器.

It's not possible to return Django model object as data. You should use serializers for this purpose.

class UserProfileSerializer(serializers.ModelSerializer):
    class Meta:
        model = UserProfile
        fields = '__all__'


class UserProfileAPIView(APIView):
    serializer_class = UserProfileSerializer
    def post(self, request):
        user = request.user
        user_profile = UserProfile.objects.get(user=user)
        serializer= self.serializer_class(user_profile)
        return Response({"success": True, "status": "Success", "data": serializer.data}, status=status.HTTP_201_CREATED)

这篇关于出现错误:用户类型的对象在Django Python中无法JSON序列化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆