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
By default it is set to False. Setting it to True will allow you to mark the field as optional during "serialization".
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.
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.
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.
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
There is a fields meta property:
class BLcontainerMergedSerializer(serializers.ModelSerializer):
container = ContainerSerializer()
class Meta:
model = BLcontainer
fields = ('field1', 'field2')
Reference: Django REST docs
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With