我是 django python 的新手,当我尝试从 3 个表获取数据时,出现错误Object of type User is not JSON serializable
,任何人都可以帮我解释为什么我会收到此错误吗?在这里我添加了我的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)
模型.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)