0

I want to have the following behavior:

# GET Request
{
  "id": 1,
  "name": "test",
  "created_date": "date",
  "completed_date": "date",
  "template": { "name" : "test" }, => nested serializers with only the field "name"
  "status": 1,
  "results": [ { __all__ }, ... ], => nested serializers with all the fields
  "groups": [ { "name" }, ... ], => nested serializers with only the field "name"
}

# POST Request
{ 
  "name": "test",
  "template": {"name":"test"}, => nested serializers with only the field "name"
  "groups": [ {"name":"test"} ], => nested serializers with only the field "name"
}

As you can see the post request doesn't have all the information that get displays. I know that some of the fields can be removed with the read_only_fields variable. But the issue here is more related to the nested serializers. I have trouble validating the data... This issue is related to this issue: Dynamic nested serializers: empty validated_data

I was wondering if using dynamic serializers and with the combination of read_only_fields was a good maintainable and readable solution: https://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields

Or should I use the following solution: Use different serializer for request and reply

PS: I found this post too which is similar to what I am trying to do: Django Rest Framework : Nested Serializer Dynamic Model Fields

Thanks again !

Regards,

S.Hary
  • 165
  • 1
  • 3
  • 15
  • If you use multiple serializers according to the request type, it will increase the readability factor a little bit than overriding the `__init__()` method. – JPG Apr 23 '19 at 16:06
  • Well most of the fields are taken care of... if I try to use dynamic serializers and read_only_fields variables. This is what I did: id, created_date, modified_date fields are automatically taken care of. results field is a read_only_field, it's taken care of with the special variable so it's only visible with the GET and not POST. Now comes the nested serializers with the dynamic serializers with only selected fields of the nested serializer are used and needed... The POST is "fine" like it request the correct fields, but the validated_data is empty. Hope you understand? – S.Hary Apr 24 '19 at 08:42
  • I think this issue is also related to this one: https://stackoverflow.com/questions/35036262/django-rest-framework-nested-serializer-dynamic-model-fields – S.Hary Apr 24 '19 at 08:43

0 Answers0