Skip to content

Fix One field that is required=False, allow_null=True and not provided. to_representation should not explicitly set it to None - #9461

Closed
LinanV wants to merge 1 commit into
encode:masterfrom
LinanV:fixed-9458
Closed

LinanV wants to merge 1 commit into
encode:masterfrom
LinanV:fixed-9458

Conversation

@LinanV

@LinanV LinanV commented Jul 8, 2024 •

Copy link
Copy Markdown

Example

Consider the following serializer and instance:

class MySerializer(serializers.Serializer):
    name = serializers.CharField()
    type = serializers.CharField(required=False, allow_null=True)
    desc = serializers.CharField(required=False, allow_null=True)

instance = {'name': 'example'}
serializer = MySerializer(instance, partial=True)
data = serializer.data
# Current output: {'name': 'example', 'desc': None, 'type': None}
# Proposed output: {'name': 'example'}

Changed

def get_attribute(self, instance
        """
        Given the *outgoing* object instance, return the primitive value
        that should be used for this field.
        """
       ...
           
            # changed
            if not self.required: 
                raise SkipField()
            if self.allow_null:
                return None**
       ...

Description

refs #9458

…d. to_representation should not explicitly set it to None

@auvipy auvipy left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

your change seems to make the tests fail. would you mind adding tests to verify the change? also in the issue I found some comment that initially discourage this change and you also shared some alternative proposals. care to chime in more? thanks

@LinanV LinanV closed this Aug 2, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Development

Successfully merging this pull request may close these issues.

2 participants