Erika
Erika

Reputation: 925

How to dynamically add `read_only = True` on a field on serializer when creating object

I have really complicated serializer (goes three levels deep), that I am using in two views. For POST and PATCH calls.

I am wondering how can I dynamically change the read_only attribute on pk field, considering the action that is performed.

If I send a POST of this data to the endpont:

{
  "id": 93,
  "name": "Template workout",
  "items": [
    {
      "id": 74,
      "is_superset": false,
      "seq": "00002",
      "exercises": [
        {
          "id": 50,
          "exercise": {
            "id": 3,
            "title": "sprint"
          },
          "set_type": "time",
          "rest": 30,
          "sets": [
            {
              "id": 141,
              "weight": null,
              "reps": null,
              "time_interval": 30
            },
            {
              "id": 142,
              "weight": null,
              "reps": null,
              "time_interval": 40
            },
            {
              "id": 143,
              "weight": null,
              "reps": null,
              "time_interval": 50
            }
          ]
        }
      ]
    }
  ]
}

I would like to remove all the id keys with values from this structure. I am thinking that sendng it trough serializer when id is read_only=True is my best bet, but I do need the ids when updating.

Upvotes: 0

Views: 183

Answers (1)

Edwin Lunando
Edwin Lunando

Reputation: 2816

You need to override the create method on your serializer http://www.django-rest-framework.org/api-guide/serializers/#saving-instances Then, inside the validated_data, you need to save the objects manually.

Upvotes: 1

Related Questions