Skip to content

dotted source on CharField returns null from to_representation when allow_null=False #5371

Closed

Description

@sassoo

Checklist

  • I have verified that that issue exists against the master branch of Django REST framework.
  • I have searched for similar issues in both open and closed tickets and cannot find a duplicate.
  • This is not a usage question. (Those should be directed to the discussion group instead.)
  • This cannot be dealt with as a third party library. (We prefer new functionality to be in the form of third party libraries where possible.)
  • I have reduced the issue to the simplest possible case.
  • I have included a failing test as a pull request. (If you are unable to do so we can still accept the issue.)

Steps to reproduce

class PersonSerializer(serializers.Serializer):
    moms_name = serializers.CharField(
        allow_blank=True,
        allow_null=False,
        default='',
        required=False,
        source='mom_props.name'
)

The instance passed to the PersonSerializer may or may not have a mom_props model relationship in the database so getting the dotted source path may raise an ObjectDoesNotExist.

Expected behavior

If mom_props.name were to return None or an ObjectDoesNotExist because in the case of django related models the mom_props model doesn't exist then moms_name should be an empty string in the output of to_representation

Actual behavior

None or null is returned instead. This is inconsistent behavior for my api consumers since moms_name returns null but null is not a valid value ever for the property. If they turn around & submit the data back then they will get a validiationerror from the data I just sent them. This is probably related to #2299 but couldn't a better default be chosen in the case of CharFields with allow_blank=True & allow_null=False?

It's also quite likely I'm doing something really dumb but what I'm trying to accomplish is a mashup of multiple django models into a single serializer so my api consumers can interact with the data more easily without having to know or care about my backend schema. Pretty common I'm sure so it's more of a flattened serializer with a not flat database schema.

Everything works great when writing & naturally I've overridden the create & update methods & elected to be more explicit using the Serializer class instead of a ModelSerializer so it's more clear what is the API's responsibilty & what is the ORM's.

Finally, the part of the code base I think would need to be tweaked is:
https://github.com/encode/django-rest-framework/blob/master/rest_framework/serializers.py#L492-L501

Activity

  1. xordoquy commented on Aug 29, 2017

    @xordoquy
    Contributor

    Hi,

    allow_null is only used for deserialization purposes. It's up to the developer to provide correct data for serialization as DRF will not perform check against since it's already supposed to be sane.

  2. sassoo commented on Aug 29, 2017

    @sassoo
    Author

    Is default only used for deserialization too? The docs say:

    When serializing the instance, default will be used if the the object attribute or dictionary key is not present in the instance.

  3. rpkilby commented on Aug 29, 2017

    @rpkilby
    Contributor

    @xordoquy - reopening this, since this seems like an edge case bug. It looks like serialization's default handling doesn't traverse relationships. As a quick test, I ran the following:

    class Serializer(serializers.Serializer):
        bar = serializers.CharField(
            allow_blank=True, 
            allow_null=False,
            default="",
            required=False, 
            source='foo.bar')
        
    >>> Serializer({}).data
    ReturnDict([('bar', '')])
    
    >>> Serializer({'foo': {}}).data
    ReturnDict([('bar', '')])
    
    >>> Serializer({'foo': None}).data
    ReturnDict([('bar', None)])
  4. sassoo commented on Aug 29, 2017

    @sassoo
    Author

    Thanks. What you just showed is what I experience as well.

  5. sassoo commented on Aug 30, 2017

    @sassoo
    Author

    Would you like me to update the issue description to better reflect default="" with dotted field sources serializes to null instead of empty string?

  6. added a commit that references this issue on Aug 30, 2017
  7. rpkilby commented on Aug 30, 2017

    @rpkilby
    Contributor

    No worries - have opened a PR for the issue.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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