簡體   English   中英

在 Django Rest Framework ModelSerializer 中指定自定義嵌套對象

[英]Specifying custom nested objects in Django Rest Framework ModelSerializer

我有 lat, long 在我的數據庫中指定為:

...
lat = models.DecimalField(_('Latitude'), max_digits=8, decimal_places=5, null=True, blank=True)
lng = models.DecimalField(_('Longitude'), max_digits=8, decimal_places=5, null=True, blank=True)
...

我希望我的 ModalSerialization 顯示為:

{
  ...
  "location": {
      "lat": ...,
      "long": ... 
  }
  ...
}

我如何做到這一點?

一種方法是您可以在如下所示的模型中創建屬性。

@property
def location_info(self):
    return dict(
        lat=self.lat,
        lng=self.lng
    )

然后您可以在序列化程序中創建一個 dict 字段並將源指定為您的屬性。 因為它是屬性,所以它可以是只讀字段。

location = serializers.DictField(source='location_info', read_only=True) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM