如何序列化嵌套对象?

时间:2020-10-17 16:56:23

标签: python django django-rest-framework

我有Django模型:

class Client(models.Model):
    name = models.CharField()

class Office(models.Model):
    name = models.CharField()

class HolidayOffer(models.Model):
    name = models.CharField()

class Booking(models.Model):
    holiday_offer = models.ForeignKey(HolidayOffer, null=True)
    office = models.ForeignKey(Office, null=True)
    client = models.ForeignKey(Client, null=True)
    start_date = models.DateField()                    
    end_date = models.DateField()

如何为API JSON构造django-rest-framework序列化程序以获取类似于以下示例的响应:

{
    "offices": [
        { 
                "name": "New York Office",
                "clients": [ 
                        { 
                                "name": "Client A",
                                "bookings": [
                                        { 
                                                "holiday_offer": {
                                                        "name": "Cyprus - Exclusive Vacation f>
                                                }
                                                "start_date": "20180608",
                                                "end_date": "20180615"
                                        }
                                ]
                        }
                ]
        }
    ]
}

可以更改模型关系。

0 个答案:

没有答案