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
- [Answered ]-Django giving error when trying to get path to static file
- [Answered ]-I want to give users ten coins each time they fill out one form
- [Answered ]-How to add "$" in a Integer Field in Django in admin interface?
- [Answered ]-Dynamic creating an "OR" Query in django
- [Answered ]-Grouping URL patterns that are similar
Source:stackexchange.com