我在自定义序列化方面遇到问题,我在文档中看了几个小时,但我无法弄清楚我会做什么。我有嵌套的序列化器对象,如下所示,但我希望有非嵌套对象,任何人都可以帮我这个吗?
嵌套对象:
{
"id": 1,
"adDate": "20-08-2016",
"price": "30.50",
"city": "Istanbul",
"latitude": "28.987509",
"longitude": "41.040353",
"isPublished": true,
"book": {
"id": 1,
"bookName": "GameOfThrones",
"category": "Adventure",
"photo": "http://localhost:8000/media/advert_images/game_of_thrones.jpg",
"description": "Adventure Book",
"author": "Emre Yavuz",
"language": "Sangridce",
"publicationDate": "2023",
"publisher": "Deu_Yapim",
"edition": "22",
"page_number": 900
}
}
非嵌套对象:
{
"id": 1,
"adDate": "20-08-2016",
"price": "30.50",
"city": "Istanbul",
"latitude": "28.987509",
"longitude": "41.040353",
"isPublished": true,
"bookName": "GameOfThrones",
"category": "Adventure",
"photo": "http://localhost:8000/media/advert_images/game_of_thrones.jpg",
"description": "Adventure Book",
"author": "Emre Yavuz",
"language": "Sangridce",
"publicationDate": "2023",
"publisher": "Deu_Yapim",
"edition": "22",
"page_number": 900
}
我的序列化程序类:
class AdvertSerializer(serializers.ModelSerializer):
book = BookSerializer()
class Meta(object):
model = Advert
fields = ('id', 'adDate', 'price',"city","latitude","longitude","isPublished",'book','seller')
depth = 2
class BookSerializer(serializers.ModelSerializer):
photo = serializers.ImageField(max_length=None,use_url=True)
class Meta(object):
model = Book
答案 0 :(得分:0)
我不知道您为什么喜欢非嵌套表示,但为了对其进行存档,您需要使用source
字段属性在序列化程序上逐个指定图书字段。< / p>
class AdvertSerializer(serializers.ModelSerializer):
book_name = serializer.CharField(source='book.bookName')
description = serializer.CharField(source='book.description')
# add the rest of the book fields in that way
class Meta(object):
model = Advert
fields = ('id', 'adDate', 'price',"city","latitude","longitude","isPublished",'book','seller')