Repository navigation
Make model fields with a db_default optional in ModelSerializer - #10086
Open
LindseyZ1205 wants to merge 1 commit into
Open
LindseyZ1205 wants to merge 1 commit into
LindseyZ1205 wants to merge 1 commit into
Conversation
A model field with a default isn't required, but a field with a db_default was, although the database fills it in.
auvipy
self-requested a review
October 24, 2026 17:01
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Description
refs #9257
ModelSerializermakes a field optional when its model field has adefault, but not when it has adb_default(new in Django 5.0), so the field is required even though the database fills it in. For example, witha
ModelSerializerwithfields = "__all__"rejects{"title": "Hello"}with "This field is required." forstatusandcreated. The workaround mentioned in #9257 is to setrequired=Falseinextra_kwargsfor each such field.This change also checks
has_db_default()whereget_field_kwargs()andget_relation_kwargs()setrequired=Falsefor a field with adefault, and addsdb_defaultto therequireddocs.Field.has_db_default()exists since Django 5.2, the oldest version DRF supports. A field with adb_defaultthat is part of a unique constraint stays required, as before, sinceUniqueTogetherValidatorneeds its value.Tests:
test_db_default_field_not_required(a constant and an expressiondb_default) andtest_foreign_key_with_db_defaultintests/test_model_serializer.pyfail without this change. The test suite passes with Django 6.1.2 and Djangomain(1656 passed, 13 skipped, on Python 3.14). With the model above, the serializer now saves{"title": "Hello"}, and the database setsstatusto"draft"andcreatedto the current time.