After having the same problem, I found a solution, I hope this will be helpul for some people. I modified DynamicFieldsModelSerializer as defined here
def __init__(self, *args, **kwargs):
# Don't pass the 'fields' arg up to the superclass
fields = kwargs.pop('fields', None)
nested = kwargs.pop('nested', None)
# Instantiate the superclass normally
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
if fields is not None:
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(self.fields.keys())
for field_name in existing - allowed:
self.fields.pop(field_name)
if nested is not None:
for serializer in nested:
try:
nested_serializer = self.fields[serializer]
except:
logger.warning("Wrong nested serializer name")
continue
allowed = set(nested[serializer])
existing = set(nested_serializer.fields.keys())
for field_name in existing - allowed:
nested_serializer.fields.pop(field_name)
After that, You can use it like this:
SerializerOne(queryset, nested={"another_field": ["name"]})
You can modify my solution to use the double underscore instead of another kewyord with a dict, but I wanted to separate regular fields from nested serializer.
It can also be improved to be recursive, here I'm only dealing with a depth of one nested serializer
EDIT
I modified my code to use the double underscore syntax after all:
def __init__(self, *args, **kwargs):
def parse_nested_fields(fields):
field_object = {"fields": []}
for f in fields:
obj = field_object
nested_fields = f.split("__")
for v in nested_fields:
if v not in obj["fields"]:
obj["fields"].append(v)
if nested_fields.index(v) < len(nested_fields) - 1:
obj[v] = obj.get(v, {"fields": []})
obj = obj[v]
return field_object
def select_nested_fields(serializer, fields):
for k in fields:
if k == "fields":
fields_to_include(serializer, fields[k])
else:
select_nested_fields(serializer.fields[k], fields[k])
def fields_to_include(serializer, fields):
# Drop any fields that are not specified in the `fields` argument.
allowed = set(fields)
existing = set(serializer.fields.keys())
for field_name in existing - allowed:
serializer.fields.pop(field_name)
# Don't pass the 'fields' arg up to the superclass
fields = kwargs.pop('fields', None)
# Instantiate the superclass normally
super(DynamicFieldsModelSerializer, self).__init__(*args, **kwargs)
if fields is not None:
fields = parse_nested_fields(fields)
# Drop any fields that are not specified in the `fields` argument.
select_nested_fields(self, fields)
You can then use it like this:
SerializerOne(instance, fields=["another_field__name"])