I have defined serializers like below. I'm using a mixin to change the display fields on the fly.
class SerializerTwo(serializers.ModelSerializer):
class Meta:
model = Two
fields = ('name', 'contact_number')
class SerializerOne(DynamicFieldsModelSerializer, serializers.ModelSerializer):
another_field = SerializerTwo()
class Meta:
lookup_field = 'uuid'
model = One
fields = ('status', 'another_field',)
Now what I want to do is, dynamically pass(on the fly) what all fields will be used from SerializerTwo, as I'm doing for SerializerOne.
The way I'm doing it for SerializerOne is:
# where fields=('status')
SerializerOne(queryset, fields=fields)
Is there a way, using which I can add fields from SerializerTwo to the above Serializer initialization.
# where fields=('status', 'name') name from SerializerTwo
# the double underscore notation does not work here for fields, so another_field__name cannot be used as well
SerializerOne(queryset, fields=fields)
After having the same problem, I found a solution, I hope this will be helpul for some people. I modified DynamicFieldsModelSerializer as defined here
After that, You can use it like this:
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:
You can then use it like this:
@Lotram's answer doesn't work on fields that return multiple values (via
many=True
).The following code improves upon @Lotram's solution which works on fields that return multiple values:
I use the following way to implement the so called
Nested Serializer Dynamic Model Fields
.and we make some modification to
DynamicFieldsModelSerializer
so the last problem is how to organize the url, write the
GET
url like this:domain/something?one_fields=name,contact_number&two_fields=another_field