2016-08-10 15 views
1

私はカスタムシリアル化に問題があり、何時間もドキュメンテーションを見ていますが、私は何をするのか分かりませんでした。以下のようなネストされたシリアライザオブジェクトがありますが、ネストされていないオブジェクトが必要です。Django-RestFrameworkカスタムSeriliazation

ネストされたオブジェクト:

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

あなたは非ネストされた表現を好む理由を私は知らないが、それをアーカイブするためには、あなたが本のフィールド、sourceフィールド属性を使用して、シリアライザの一つ一つを指定する必要があります。

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') 
関連する問題