From the course: Building RESTful Web APIs with Django

Unlock the full course today

Join today to access over 22,600 courses taught by industry experts or purchase this course individually.

Serializer with only selected fields

Serializer with only selected fields

From the course: Building RESTful Web APIs with Django

Start my 1-month free trial

Serializer with only selected fields

- In the product serializer, we already have selected some fields for rendering through the serializer. However, we can do a little bit of refactoring to simplify how we added custom field data. We can take the attributes that we set in the two representation method and refactor them using serializer fields. We have a boolean field for is on sale. It is a read-only field. And for the current price, we have a float field which is also read-only. We can now delete two representation and add the fields to metafields so that they appear in the serializer. The read-only serializer field configuration parameter sets whether or not we can write to the field through the serializer. Another example of a serializer field configuration is the source keyword argument. This can be used if you want to rename a field. For instance, if you want the rest API to return a field called 'product name' rather than just 'name'. Back to the code, we can add a description field that overrides the serializer…

Contents