[Answered ]-How do I write to nested parent in Django Serializer

1๐Ÿ‘

I hate answering my own question, but the solution was to subclass serializers.RelatedField, which is explained in advanced-serializer-usage).

This lets you separately control how the value(instance) is represented as serialised, and how the serialised data is used to retrieve or create a value (instance).

class BiomarkerDescriptionSerializer(serializers.RelatedField):

    def to_representation(self, value):
        data = {}
        for field in ('id', 'low_value_description', 'high_value_description'):
            data[field] = getattr(value, field)
        return data

    def to_internal_value(self, data):
        return Biomarker.objects.get(id=data)

    def get_queryset(self, *args):
        pass

class BiomarkerReadingSerializer(serializers.ModelSerializer):
    biomarker = BiomarkerDescriptionSerializer()
    ...

The overridden get_queryset is required, even though it does nothing.

This means data going in looks like this:

{
    "id": 617188,
    "test" 71829, 
    "biomarker": 32,
    "value": 0.001
}

Yet the data going out looks like this:

{
    "id": 617188,
    "test" 71829, 
    "biomarker": {
        "id": 32,
        "low_value_description": "All good",
        "high_value_description": "You will die",
    },
    "value": 0.001
}

Thank you to those who offered answers, much appreciated

๐Ÿ‘คandyhasit

0๐Ÿ‘

Using depth = 1 option will solve your problem.

class BiomarkerReadingSerializer(serializers.ModelSerializer):
    class Meta:
        model = BiomarkerReading
        fields = (
            'id', 'test', 'biomarker', 'value'
        )
        depth = 1

Take a look: https://www.django-rest-framework.org/api-guide/serializers/#specifying-nested-serialization

๐Ÿ‘คadnan kaya

Leave a comment