问题
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
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)
回答1:
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)
来源:https://stackoverflow.com/questions/59433895/getting-error-object-of-type-user-is-not-json-serializable-in-django-python