我有兩個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)
感謝
在您的視圖中使用了'Book'類對象(不是模型),而是將其分配給模型中的行(user.basket.books?) –