Skip to content

Make model fields with a db_default optional in ModelSerializer - #10086

Open
LindseyZ1205 wants to merge 1 commit into
encode:mainfrom
LindseyZ1205:fix/db-default-not-required
Open

LindseyZ1205 wants to merge 1 commit into
encode:mainfrom
LindseyZ1205:fix/db-default-not-required

Conversation

@LindseyZ1205

Copy link
Copy Markdown

Description

refs #9257

ModelSerializer makes a field optional when its model field has a default, but not when it has a db_default (new in Django 5.0), so the field is required even though the database fills it in. For example, with

from django.db import models
from django.db.models.functions import Now


class Article(models.Model):
    title = models.CharField(max_length=100)
    status = models.CharField(max_length=10, db_default="draft")
    created = models.DateTimeField(db_default=Now())

a ModelSerializer with fields = "__all__" rejects {"title": "Hello"} with "This field is required." for status and created. The workaround mentioned in #9257 is to set required=False in extra_kwargs for each such field.

This change also checks has_db_default() where get_field_kwargs() and get_relation_kwargs() set required=False for a field with a default, and adds db_default to the required docs. Field.has_db_default() exists since Django 5.2, the oldest version DRF supports. A field with a db_default that is part of a unique constraint stays required, as before, since UniqueTogetherValidator needs its value.

Tests: test_db_default_field_not_required (a constant and an expression db_default) and test_foreign_key_with_db_default in tests/test_model_serializer.py fail without this change. The test suite passes with Django 6.1.2 and Django main (1656 passed, 13 skipped, on Python 3.14). With the model above, the serializer now saves {"title": "Hello"}, and the database sets status to "draft" and created to the current time.

A model field with a default isn't required, but a field with a
db_default was, although the database fills it in.
@auvipy
auvipy self-requested a review October 24, 2026 17:01

This branch has not been deployed

No deployments
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.

1 participant