Automatically add all model fields to django rest serializer

3.3k Views Asked by At

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)

2

There are 2 best solutions below

2
On BEST ANSWER

By default, the ModelSerializer returns all model fields if fields argument is not defined in the Meta.
Similarly for normal serializers.Serializer, it will return all the fields defined in the serializer(except read-only fields).

You have to specify fields in your Meta class only if you want a subset of all the fields to be returned.

(From the DRF docs)

If you only want a subset of the default fields to be used in a model serializer, you can do so using fields or exclude options.

So just don't specify the fields argument in your Meta class and it should return all the fields.

0
On

What you need is the list of fields from the model. It is reachable in model._meta.fields. At this point, you may add the field address if it's not part of your model.

Even better, with django 1.8, you can use model.get_fields. doc