【问题标题】:Getting error : Object of type User is not JSON serializable in django python出现错误:用户类型的对象在 django python 中不是 JSON 可序列化的
【发布时间】:2020-04-13 11:27:52
【问题描述】:

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

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)

【问题讨论】:

标签: python django django-models django-rest-framework django-views


【解决方案1】:

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

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 rest framework 文档然后开始编码。
  • @NikulPanchal from rest_framework.views import APIView
猜你喜欢
  • 2021-06-07
  • 2019-04-29
  • 2020-12-02
  • 2021-12-24
  • 2018-10-28
  • 2022-01-23
  • 2023-03-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多