Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exclude a field from django rest framework serializer

In the following serializer, I have a nested serializer [ContainerSerializer] field and I want to exclude a field from (container)ContainerSerializer but I don't want any change in ContainerSerializer. How can I do that?

class BLcontainerMergedSerializer(serializers.ModelSerializer):
    container = ContainerSerializer()
    class Meta:
        model = BLcontainer
like image 588
Minuddin Ahmed Rana Avatar asked Jul 14 '16 06:07

Minuddin Ahmed Rana


People also ask

How do you make a serializer optional in Django?

By default it is set to False. Setting it to True will allow you to mark the field as optional during "serialization".

How do I pass Queryset to serializer?

To serialize a queryset or list of objects instead of a single object instance, you should pass the many=True flag when instantiating the serializer. You can then pass a queryset or list of objects to be serialized.

How do you pass extra context data to Serializers in Django REST framework?

In function based views we can pass extra context to serializer with "context" parameter with a dictionary. To access the extra context data inside the serializer we can simply access it with "self. context". From example, to get "exclude_email_list" we just used code 'exclude_email_list = self.

What does serializer save () do?

So everytime you call Serializer's save() , you get an instance of whatever data you are serializing. comment here is an instance. Passing an instance in a serializer is telling the serializer that you want to update this instance. So calling save will then call self.


2 Answers

Create another serializer say BLContainerSerializer and exclude fields there. Then use this in your BLcontainerMergedSerializer. Hope this helps.

class BLContainerSerializer(serializers.ModelSerializer):     class Meta:         model = Container         exclude = ('field1', )   class BLcontainerMergedSerializer(serializers.ModelSerializer):     container = BLContainerSerializer()      class Meta:         model = BLcontainer 
like image 130
Dineshs91 Avatar answered Sep 18 '22 13:09

Dineshs91


There is a fields meta property:

class BLcontainerMergedSerializer(serializers.ModelSerializer):
    container = ContainerSerializer()
    class Meta:
        model = BLcontainer
        fields = ('field1', 'field2')

Reference: Django REST docs

like image 22
Wtower Avatar answered Sep 18 '22 13:09

Wtower