我希望具有以下行为:
# 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"
}
您可以看到,发帖请求并没有显示所有信息。我知道可以使用read_only_fields
变量删除某些字段。但是,这里的问题与嵌套序列化器更多有关。我无法验证数据...此问题与以下问题有关:Dynamic nested serializers: empty validated_data
我想知道使用动态序列化程序和read_only_fields
的组合是否是一个很好的可维护性和可读性的解决方案:
https://www.django-rest-framework.org/api-guide/serializers/#dynamically-modifying-fields
或者我应该使用以下解决方案:Use different serializer for request and reply
PS:我也发现了这篇帖子,与我尝试做的类似:Django Rest Framework : Nested Serializer Dynamic Model Fields
再次感谢!
此致