在APIView上显示对象

时间:2018-03-29 02:28:33

标签: python django

我有一个模型,我只想在/ api /

中显示模型的数据
from django.db import models
from rest_framework.authtoken.models import Token
from django.contrib.auth.models import User

class Book(models.Model):
    order_id = models.IntegerField()
    isbn = models.IntegerField()
    publisher = models.CharField(max_length=256)
    school = models.CharField(max_length=256)
    price = models.IntegerField()
    duration = models.CharField(max_length=10)
    order_datetime = models.DateTimeField(auto_now=False, auto_now_add=False)

    def __str__(self):
        return str(self.order_id)

这是我的urls.py:

from django.contrib import admin
from django.urls import path
from filter import views

urlpatterns = [
    path('', views.index, name='index'),
    path('api/', views.BookApiView.as_view(), name='book_api'),
    path('admin/', admin.site.urls),
]

这是我的views.py:

from django.shortcuts import render
from rest_framework.views import APIView
from .models import Book
from django.http import JsonResponse


class BookApiView(APIView):
    def get(self, request, format=None):
        books = Book.objects.all()
        return JsonResponse({'model': list(books)})

我收到以下错误:'对象的类型' Book'不是JSON可序列化的'

此致

安东尼

3 个答案:

答案 0 :(得分:1)

Django模型不能隐式地进行JSON序列化。

您需要一个序列化程序将模型转换为JSON可序列化的表示形式(原始字母,列表,数字,字符串等)

Django rest framework serializer docs:http://www.django-rest-framework.org/api-guide/serializers/

class BookSerializer(serializers.Serializer):
    order_id = serializers.IntegerField()
    isbn = serializers.CharField()
    ...

class BookApiView(APIView):
    def get(self, request, format=None):
        books = Book.objects.all()

        serializer = BookSerializer(books, many=True)

        return JsonResponse({'model': serializer.data})

答案 1 :(得分:1)

男人......你需要一个' Serializer'在将数据发送到视图之前! Serializez类从django ORM获取抽象数据,并轻松地将数据解析为JSON。

在view.py的同一级别创建一个文件serializers.py 和

from rest_framework import serializers

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        model = Book
        fields = '__all__'

创建SerializerBook类后,将其导入视图并将book queryset作为BookSerializer的第一个参数传递。

...
class BookApiView(APIView):
    def get(self, request, format=None):
        books = Book.objects.all()
        serializer = BookSerializer(books, many=True)
        return Response(serializer.data)

答案 2 :(得分:1)

您应该定义serializer以将模型实例数据转换为相应的JSON数据。因此,如下所示定义serializer.py

class BookSerializer(serializers.ModelSerializer):
    class Meta:
        fields = '__all__'
        model = Book


then in your view, change as below,<br>
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Book


class BookApiView(APIView):
    def get(self, request, format=None):
        booksqueryset = Book.objects.all()
        serializer = BookSerializer(booksqueryset, many=True)
        return Response(data=serializer.data)


阅读此DRF ModelSerializer Official Doc了解更多详情