Hi all,
I'm troubleshooting a bug in the drf-spectacular library that we're trying to use to generate Open Api 3.0 schemas from our DRF codebase (link:
https://github.com/tfranzel/drf-spectacular/issues/422), and I stumbled across what looks like a bit of an inconsistency in what arguments are expected to be passed to the to_representation function on different field types.
for field
in fields:
try:
attribute = field.get_attribute(instance)
except SkipField:
continue
# We skip `to_representation` for `None` values so that fields do
# not have to explicitly deal with that case.
#
# For related fields with `use_pk_only_optimization` we need to
# resolve the pk value.
check_for_none =
attribute.pk if isinstance(attribute, PKOnlyObject)
else attribute
if check_for_none
is None:
ret[field.field_name] =
None
else:
ret[field.field_name] = field.to_representation(attribute)
What is interesting, is that different fields return different types from the call to field.get_attribute. Most fields seem to fetch the attribute from the instance that is passed in and return the attribute. Some fields however, like ModelField and SerializerMethodField, just return the instance, without fetching an attribute.
This means that the to_representation functions for ModelField and SerializerMethodField expect the entire instance to be passed in as the argument, whereas most fields expect just the attribute.
Is this different signature for Field.to_representation expected? And are there any suggestions for how to handle it, perhaps there is a way to know which fields have different signatures?
We're trying to use to_representation to make sure that we're using primitive types when generating the Open API schemas.
Thanks for the help,
Russell