Be careful with default values in DRF

Default values are nice, because we don’t want to set every single detail on a new remote all the time. But here’s an issue. When we specify default values on the drf serializer fields, this is not only duplicated information, because the db models should have the proper defaults already. They will also be propagated into the openapi schema, and now be used by the generated clients. On a create or update call this is not obviously wrong, but on patch calls, these default values tend to inadvertently reset values the users didn’t intent to touch. We could now have an argument whether drf-spectacular translates the serializers wrongly into the patched schemata, but we can just mark all the fields with a default in the db to not be required on the serializer.

So when you see this:

sync_dependencies = serializers.BooleanField(
    help_text=_("Sync dependencies for collections specified via requirements file"),
    default=True,
)

please change it to

sync_dependencies = serializers.BooleanField(
    help_text=_("Sync dependencies for collections specified via requirements file"),
    required=False,
)
2 Likes

When adjusting, take a moment to think of there’s code using the serializer that “assumes things” about serializer-defaults.

3 Likes