如何解决代码中的“对象无法json序列化的对象”问题?

时间:2019-04-14 04:49:58

标签: django django-models django-serializer

我是一个尝试学习Django的初学者。我被这个错误困住了,这是我的模型无法json序列化的错误。我确实尝试过对模型进行序列化,并且已经附加了序列化器类,但是看来我做的方式有问题。

我该如何解决这个问题?

这是我的模特

class Portfolio(models.Model):
    # user_id = models.CharField(primary_key=True, max_length=100)
    cash_bal = models.DecimalField(max_digits=19, decimal_places=2, 
    default=Decimal('0'))
    birthday = models.DateField()
    gender = models.CharField(max_length=5, null=True)
    hometown = models.CharField(max_length=300, null=True)
    username = models.CharField(max_length=100)

这是我的序列化器:

from rest_framework import serializers
from .models import Portfolio


class PortfolioSerializer(serializers.ModelSerializer):

    class Meta:
        model = Portfolio
        fields = 'id'

这是我的views.py:

from django.shortcuts import render,get_object_or_404
from .models import *
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from .serializers import PortfolioSerializer
from django.views.decorators.csrf import csrf_exempt

@csrf_exempt
def userlogin(request):
    if request.method == "POST":

        print(request.POST)
        if not 
        Portfolio.objects.filter(username=request.POST['name']).exists() and 
        not 
        Portfolio.objects.filter(birthday=request.POST['birthday']).exists():

            obj = Portfolio.objects.create(username=request.POST['name'],
                                           birthday=request.POST['birthday'],
                                           email=request.POST['email'],
                                           hometown='none',
                                           cash_bal='0')
            serializer = PortfolioSerializer(obj)

        else:
            obj1 = Portfolio.objects.filter(email=request.POST['email'])
            obj = get_object_or_404(obj1, birthday=request.POST['birthday'])
            serializer = PortfolioSerializer(obj)

        request.session['user'] = obj
        request.session['logged_in'] = True
        request.session.save()
        return Response(serializer.data)

这是错误:

Internal Server Error: /khelo/userlogin/
Traceback (most recent call last):
  File "F:\backend\venv\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "F:\backend\venv\lib\site-packages\django\core\handlers\base.py", line 126, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "F:\backend\venv\lib\site-packages\django\core\handlers\base.py", line 124, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "F:\backend\venv\lib\site-packages\django\views\decorators\csrf.py", line 54, in wrapped_view
    return view_func(*args, **kwargs)
  File "F:\backend\khelo\common\views.py", line 46, in userlogin
    request.session.save()
  File "F:\backend\venv\lib\site-packages\django\contrib\sessions\backends\db.py", line 81, in save
    return self.create()
  File "F:\backend\venv\lib\site-packages\django\contrib\sessions\backends\db.py", line 55, in create
    self.save(must_create=True)
  File "F:\backend\venv\lib\site-packages\django\contrib\sessions\backends\db.py", line 83, in save
    obj = self.create_model_instance(data)
  File "F:\backend\venv\lib\site-packages\django\contrib\sessions\backends\db.py", line 70, in create_model_instance
    session_data=self.encode(data),
  File "F:\backend\venv\lib\site-packages\django\contrib\sessions\backends\base.py", line 96, in encode
    serialized = self.serializer().dumps(session_dict)
  File "F:\backend\venv\lib\site-packages\django\core\signing.py", line 87, in dumps
    return json.dumps(obj, separators=(',', ':')).encode('latin-1')
  File "F:\python\lib\json\__init__.py", line 238, in dumps
    **kw).encode(obj)
  File "F:\python\lib\json\encoder.py", line 199, in encode
    chunks = self.iterencode(o, _one_shot=True)
  File "F:\python\lib\json\encoder.py", line 257, in iterencode
    return _iterencode(o, 0)
  File "F:\python\lib\json\encoder.py", line 179, in default
    raise TypeError(f'Object of type {o.__class__.__name__} '
TypeError: Object of type Portfolio is not JSON serializable

Views.py:

  @csrf_exempt
def userlogin(request):
    if request.method == "POST":

        print(request.POST)
        if not Portfolio.objects.filter(username=request.POST['name']).exists() and not Portfolio.objects.filter(birthday=request.POST['birthday']).exists():

            obj = Portfolio.objects.create(username=request.POST['name'],
                                           birthday=request.POST['birthday'],
                                           email=request.POST['email'],
                                           hometown='none',
                                           cash_bal='0')
            #data = serializers.serialize('json', [obj, ])
            data = {'id': obj.id}
        else:
            obj1 = Portfolio.objects.filter(email=request.POST['email'])
            obj = get_object_or_404(obj1, birthday=request.POST['birthday'])
            #data = serializers.serialize('json', [obj, ])
            #return JsonResponse({'error': 'user already exists'})
            data = {'id': obj.id}
        request.session['user'] = obj
        request.session['logged_in'] = True
        request.session.save()
        return JsonResponse({'data': data})

urls.py
        from django.contrib import admin
from django.urls import path
from django.conf.urls import url
from rest_framework.urlpatterns import format_suffix_patterns
from common import views

urlpatterns = [
    path('admin/', admin.site.urls),
    url(r'^khelo/userlogin/$', views.userlogin)
]

0 个答案:

没有答案