List不是JSON可序列化的

时间:2017-05-24 17:26:25

标签: python json django serialization django-rest-framework

我有两个班级书和篮子。在这种情况下,篮子有不止一本书。我必须按正确的顺序序列化它们。我写了一个序列化查询,但它不起作用。当我尝试运行runserver时,它返回

  

homepage.views.Book对象0x7f1afe3a8ef0不是JSON可序列化的

class Book(object):
    def __init__(self,bookId,bookName,bookPrice,bookAuthor,bookYear,bookStar,bookCatagory):
        self.bookId=bookId
        self.bookName=bookName
        self.bookPrice=bookPrice
        self.bookAuthor=bookAuthor
        self.bookYear=bookYear
        self.bookStar=bookStar
        self.bookCatagory=bookCatagory



class Basket(object):
    def __init__(self):
        self.numberOfProduct = None
        self.validate = None
        self.paymentValidate = None
        self.books = list()


class UserClass(object):
    def __init__(self,id,name,surname,address):
        self.id = id
        self.name = name
        self.surname = surname
        self.address = address
        self.basket = Basket()

def dummy(user):
      book = Book("1","1984","20TL","George Orwell","1999","4","Drama")
book1 = Book("2", "Verwandlung", "25TL", "Franz Kafka", "2001", "5", "Drama")
book2 = Book("3", "Game of Thrones", "50TL", "George Martin", "2007", "5", "Drama")
    user.basket.books.append(book)
    user.basket.books.append(book1)
    user.basket.books.append(book2)


@api_view(['GET'])
def test(request):
    query = User.objects.filter(userName="berkin768").first()
    if (query != None):
        userId = query.userId
        name = query.name
        surname = query.surname
        address = query.address
        newUser = UserClass(userId, name, surname, address)
        dummy(newUser)

        serializer_class = BasketSerializer(
            data={'userId': newUser.id, 'name': newUser.name, 'surname': newUser.surname, 'address': newUser.address,'book': newUser.basket.books})
        serializer_class.is_valid()

    return Response(serializer_class.data)

串行

class BookSerializer(serializers.Serializer):
    bookId = serializers.IntegerField()


class BasketSerializer(serializers.Serializer):
    userId = serializers.IntegerField()
    name = serializers.CharField(max_length=21)
    surname = serializers.CharField(max_length=21)
    address = serializers.CharField(max_length=51)
    book = BookSerializer(many=True)

由于

2 个答案:

答案 0 :(得分:0)

此代码用于反序列化。

对于您尝试执行的序列化,请替换

serializer_class = BasketSerializer(
        data={'userId': newUser.id, 'name': newUser.name, 'surname': newUser.surname, 'address': newUser.address,'book': newUser.basket.books})
serializer_class.is_valid()

由:

serializer_class = BasketSerializer(
        instance={'userId': newUser.id, 'name': newUser.name, 'surname': newUser.surname, 'address': newUser.address,'book': newUser.basket.books})

答案 1 :(得分:0)

你的类需要继承Django的model.Models。

from django.db import models

例如:

class Book(models.Model): bookId= models.IntegerField() bookName= models.CharcField() ...

这样,Django Rest Framework将序列化。 :)