Skip to content

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

Open
@LinanV

Description

@LinanV

Problem Statement

Currently, one field that isrequired=False, allow_null=True and not provided. to_representation should not explicitly set it to None.

Maybe

rest_framework/fields.py

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**
       ...

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'}

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions