Specifying custom nested objects in Django Rest Framework ModelSerializer
<p>I have lat, long specified in my DB as:</p>

<pre><code>...
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)
...
</code></pre>

<p>I want my ModalSerialization to come out as:</p>

<pre><code>{
  ...
  "location": {
      "lat": ...,
      "long": ... 
  }
  ...
}
</code></pre>

<p>How do I achieve that?</p>

<p>One of the way is you can create a property in a model like below.</p>

<pre><code>@property
def location_info(self):
    return dict(
        lat=self.lat,
        lng=self.lng
    )
</code></pre>

<p>Then you can create a dict field in your serializer and specify source as your property. Since it is property it can be readonly field.</p>

<pre><code>location = serializers.DictField(source='location_info', read_only=True) 
</code></pre>

python django django-rest-framework