I am trying to have a serializer of a Parent model, with a nested serializer as a field, being different regarding another string field.
For example, if the registry_type field is equal to intra I want to use _IntraRegistrySerializer to serialize/deserialize the registry_data field, but if registry_type is equal to slack, I want to use _SlackRegistrySerializer for the same field.
I managed to have the serialization working doing this:
class RegistrySerializer(serializers.ModelSerializer):
def to_representation(self, instance):
data = super().to_representation(instance)
if isinstance(instance, IntraRegistry):
data["registry_type"] = "intra"
data["registry_data"] = _IntraRegistrySerializer(instance=instance).data
if isinstance(instance, SlackRegistry):
data["registry_type"] = "slack"
data["registry_data"] = _SlackRegistrySerializer(instance=instance).data
return data
class Meta:
# `Registry` being the parent model of both `IntraRegistry` and `SlackRegistry`
model = Registry
fields = ["id", "description"]
But it only does half of what I would like to do.
I tried overloading methods, using SerializerMethodField, and even though I keep on searching and reading the doc I can't manage to find a solution.