1👍
✅
You can use to_representation
to override the serialization. You can then remove the entries with None
value.
class ProfileProductsSerializer(serializers.ModelSerializer):
video_product = VideoProductSerializer(read_only=True)
image_product = ImageProductSerializer(read_only=True)
class Meta:
model = ProfileProduct
fields = ['id', 'video_product', 'image_product']
def to_representation(self, instance):
data = super().to_representation()
return {k: v for k, v in data.items() if v is not None}
Source:stackexchange.com