![]() |
VOOZH | about |
In Django REST Framework (DRF), ModelSerializer simplifies creating API endpoints by automatically mapping our model's fields to the API. You can customize the data shown with two important attributes: fields, which define which fields to include, and read_only_fields, which ensures certain fields can only be viewed and not modified.
Table of Content
The fields attribute in Django REST Framework allows you to select specific model fields to include in your API response. By default, all fields from the model are shown, but you can customize it to display only the necessary data.
The read_only_fields attribute lists the fields that can only be viewed in the API response but cannot be changed by the user. This ensures that these fields are protected from modification in POST, PUT, or PATCH requests.
Feature | fields | read_only_fields |
|---|---|---|
Purpose | Determines which fields are included in the response. | Specifies fields that are read-only. |
Default Behavior | All fields are included by default. | No fields are read-only by default. |
Modification | Clients can modify fields specified in fields. | Clients cannot modify fields specified in read_only_fields. |
Use Cases | Exposing a subset of fields for performance or security reasons. | Protecting sensitive or calculated fields from modification. |
By understanding the fields and read_only_fields attributes, you can effectively control which data is exposed through your DRF API endpoints and ensure that sensitive or calculated fields are protected from unauthorized modifications.