“菜单”类型的对象不可JSON序列化

时间:2018-06-23 07:47:01

标签: django django-rest-framework

我使用Django Rest框架制作了简单的api。

[models.py]

from django.db import models

class Menu(models.Model):
    place = models.CharField(max_length=20, primary_key=True)
    mon = models.CharField(max_length=3000)
    tue = models.CharField(max_length=3000)
    wed = models.CharField(max_length=3000)
    thu = models.CharField(max_length=3000)
    fri = models.CharField(max_length=3000)
    sat = models.CharField(max_length=3000)
    sun = models.CharField(max_length=3000)

[serializers.py]

from rest_framework import serializers
from . import models

class MenuSerializer(serializers.ModelSerializer):
    class Meta:
        model = models.Menu
        fields = '__all__'

[urls.py]

from django.conf.urls import url
from django.urls import path
from . import views

urlpatterns = [
    path('', views.Menu.as_view(), name='menu')
]

[views.py]

from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from . import models

class Menu(APIView):
    def get(self, request, format=None):
        all_menu = models.Menu.objects.all()

        return Response(status=status.HTTP_200_OK, data=all_menu)

当我连接到/ menu时,它会抛出

TypeError at /menu/
Object of type 'Menu' is not JSON serializable

我该如何解决这个问题?

1 个答案:

答案 0 :(得分:2)

您正试图直接作为响应查询集传递。但是queryset不是可序列化的对象。这就是为什么您需要序列化器。

只需序列化数据,然后将其作为序列化器类的响应返回即可,

class Menu(APIView):
    def get(self, request, format=None):
        all_menu = models.Menu.objects.all()
        serializer = MenuSerializer(all_menu, many=True)  
        return Response(data=serializer.data, status=status.HTTP_200_OK)