Django-RestFramework自定义Seriliazation

时间:2016-08-10 00:14:01

标签: django serialization django-rest-framework

我在自定义序列化方面遇到问题,我在文档中看了几个小时,但我无法弄清楚我会做什么。我有嵌套的序列化器对象,如下所示,但我希望有非嵌套对象,任何人都可以帮我这个吗?

嵌套对象:

{
    "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

1 个答案:

答案 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')