获取错误:用户类型的对象在 django python 中不是 JSON 可序列化的

tak*_*aks 2 python django django-models django-views django-rest-framework

我是 django python 的新手,当我试图从 3 个表中获取数据时,出现错误Object of type User is not JSON serializable,谁能帮助我为什么会出现此错误?在这里我添加了我的views.pymodels.py文件

视图.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)
Run Code Online (Sandbox Code Playgroud)

模型.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)
Run Code Online (Sandbox Code Playgroud)

mtf*_*mtf 8

无法将 Django 模型对象作为数据返回。为此,您应该使用序列化程序。

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)
Run Code Online (Sandbox Code Playgroud)

  • @NikulPanchal 来自rest_framework.views导入APIView (2认同)