When i define a ModelSerializer the meta class can be used for defining fields which are to be serialized it automagically inherits all fields in the Model:
class ClientSerializer(ModelSerializer):
class Meta:
model = Client
I have to build a nested serializer (based on a SerializerMethodField). So i have to define the fields which to include:
class ClientSerializer(ModelSerializer)
address = SerializerMethodField('get_client_addresses')
class Meta:
model = Client
fields = ('address','name','city', <etc*>)
def get_client_addresses(self, obj):
addresses = Addresses.objects.all().filter(parent=obj)
serializer = AddressSerializer(addresses, many=True,
context={'request', self.context.get('request') })
return serializer.data
Question: In this case i have to manually add all client-fields to the fields-tuple. I don't want to do that since it seems pretty repetatative and fault sensitive. How can i add a "plus-1" field (in this case address) to the default fields that are included when a ModelSerialzer is used???
note: this is a simplified example. I have models with 40+ fields and i have to use a SerializerMethodField for the nested models, since i have to pass the context data (user-info) to the serializer for field-level authentication i have implemented.
(update, address is a SerializerMethodField, got names mixed up)
By default, the
ModelSerializer
returns all model fields iffields
argument is not defined in theMeta
.Similarly for normal
serializers.Serializer
, it will return all the fields defined in the serializer(exceptread-only
fields).You have to specify
fields
in yourMeta
class only if you want a subset of all the fields to be returned.(From the DRF docs)
So just don't specify the
fields
argument in yourMeta
class and it should return all the fields.