ModelSerializer inconsistently serializes UUID foreign keys #8786
Unanswered
r-thomson
asked this question in
Potential Issue
Replies: 1 comment 3 replies
-
That looks interesting! can you start a PR with a failing test case? |
Beta Was this translation helpful? Give feedback.
3 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
I'm working in a REST Framework app that's using UUIDs for primary keys, and I've run into some unexpected behavior with the way
ModelSerializer
handles foreign keys. I think it's worth considering changing this behavior to make things more consistent.Example
Model File
Serializer File
If we look at the fields that get generated by
ModelSerializer
, we can see that the fields are mapped as so:id
(models.UUIDField
) becomesserializers.UUIDField
related
becomesserializers.PrimaryKeyRelatedField
related_id
becomesserializers.ReadOnlyField
If we serialize a
PrimaryModel
instance, we can see that we actually get different types in the response:id
becomes astr
, while the rest becomeUUID
s.In practice,
JSONRenderer
will convert anyUUID
object to strings, so it makes no difference for the public API. However, it definitely introduces some friction when working with the serializer data directly, like when writing tests.Suggested Solution
I think the most sensible behavior here would be for the
pk_field
kwarg onPrimaryKeyRelatedField
to be automatically set toserializers.UUIDField
if the foreign key's type is a UUID, unless the user explicitly sets it to something else. This could be controlled by a setting to avoid breaking changes.While the behavior of
related_id
here is still a bit of a gotcha, I think it ultimately makes sense given the behavior ofReadOnlyField
.Beta Was this translation helpful? Give feedback.
All reactions