Skip to content

ModelSerializer fields don't obey default from the model #4703

@gcbirzan

Description

@gcbirzan

Currently, in django, even if a field doesn't have an explicit default=None, the implicit default is going to be None (technically, it's django.db.models.fields.NOT_PROVIDED). However, even if an explicit default is set on a field on the model, the serializer will ignore it.

This comes up in the context of PUT/PATCH, where one will (I know I did) expect PUT to put the default value for fields not passed that, at the very least, have an explicit default.

To give an example, a model with a field that is:

foo = models.PositiveSmallIntegerField(null=True, blank=True, default=42)

will generate the following field in the serializer:

foo = IntegerField(allow_null=True, max_value=32767, min_value=0, required=False)

The default value will be used when creating the instance, but not on PUT updates.

So, two things need to be discussed/decided:

  • Should fields that have an explicit default move that on to the serializer so that a PUT will populate the default value? - I would say a definite yes here, the current behaviour is surprising and undocumented (Or, I couldn't find it in the docs)
  • Should fields with implicit default (django.db.models.fields.NOT_PROVIDED) behave similarly and null out fields not provided for a PUT? - I would say no here, this is too big a change in behaviour and also might be surprising to other people.

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