2017-05-24 44 views
0

我有两个Book和Basket类。在这种情况下,篮子里有不止一本书。我必须按照正确的顺序将它们序列化。我写了一个序列化查询,但它不起作用。当我尝试的runserver,那么返回0x7f1afe3a8ef0列表不是JSON可序列化的

homepage.views.Book对象不是JSON序列化

CLASSES

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) 

感谢

+0

在您的视图中使用了'Book'类对象(不是模型),而是将其分配给模型中的行(user.basket.books?) –

回答

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}) 
0

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

from django.db import models

例如:

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

这样,Django的REST框架会序列。 :)