Closed gnuletik closed 4 years ago
How to pass serializer's model item
as argument such as obj
argument of SerializerMethodField
would do in a HyperlinkedModelSerializer
?
class WaveformSerializer(serializers.Serializer):
"""Populate waveform"""
... # Fields definition
d̶e̶f̶ ̶_̶_̶i̶n̶i̶t̶_̶_̶(̶s̶e̶l̶f̶,̶ ̶i̶t̶e̶m̶)̶:̶
s̶e̶l̶f̶.̶i̶t̶e̶m̶ ̶=̶ ̶i̶t̶e̶m̶
def to_representation(self, instance):
...
do_something_with(s̶e̶l̶f̶.̶i̶t̶e̶m̶ instance)
...
class ItemWaveformSerializer(ItemSerializer):
class Meta:
model = ts.models.Item
waveform = WaveformSerializer(I̶T̶E̶M̶_̶N̶E̶E̶D̶E̶D̶)
instance
argument of to_representation
is enough,
nested field need further arguments, see source
doc:
waveform = WaveformSerializer(
source='*',
many=False,
read_only=True,
)
Thanks for this @Tointoin !
However, it seems that the schema export the min_values
and max_values
(from the WaveformSerializer
).
Should it be replaced with min
and max
?
Currently, MethodSerializers are used to return dicts. For example, in
audio_url
andwaveform
. Other occurrences may exist.The issue with this technique is that the auto-generated schema do not have knowledge of the return type of the method. So, in the schema, MethodFields have a string type. e.g waveform is a string https://sandbox.wasabi.telemeta.org/timeside/redoc/#operation/RetrieveItem
In order to workaround this, we should use nested serializers. In order to keep the initial implementation, the
.to_representation
of the serializer method can be overridden.