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
  
        
    
Uh oh!
There was an error while loading. Please reload this page.
-
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
ModelSerializerhandles 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.UUIDFieldrelatedbecomesserializers.PrimaryKeyRelatedFieldrelated_idbecomesserializers.ReadOnlyFieldIf we serialize a
PrimaryModelinstance, we can see that we actually get different types in the response:idbecomes astr, while the rest becomeUUIDs.{ 'id': 'a04f3708-35b7-4ae6-98c5-56e7a598de85', 'related': UUID('1e5aa453-b351-4d56-a2c1-cf5697a4892b'), 'related_id': UUID('6100547b-f0ac-4ab2-be8c-23076fee2741') }In practice,
JSONRendererwill convert anyUUIDobject 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_fieldkwarg onPrimaryKeyRelatedFieldto be automatically set toserializers.UUIDFieldif 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_idhere 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