Fix blank=True fields in unique constraints being treated as required - #10039
Fix blank=True fields in unique constraints being treated as required#10039MehrazRumman wants to merge 2 commits into
blank=True fields in unique constraints being treated as required#10039Conversation
auvipy
left a comment
There was a problem hiding this comment.
did you check this comment of the previous pr #9751 (review) ?
|
I am checking the comments ! |
|
Yes, thanks for pointing to it. That review asked for a test on This PR already included that scenario, and I have now renamed the test to The |
|
can you please cross check if this issues is related to this #7489 ? or should be addressed in a separate pr |
|
@auvipy I checked #7489 and reproduced it on the current branch. It is a separate, pre-existing bug in This PR only changes Because the two fields with defaults now share the same path, fixing #7489 in the validator would automatically cover blank fields too. I think #7489 should be handled in its own PR since it needs a decision on whether an omitted constraint field on PUT should mean "keep the instance value" or "reset to the default", which affects what gets saved as well as what gets validated. I'm happy to open that follow-up PR if you'd like. |
Fixes #9750
Supersedes #9751
Description
Since 3.15,
ModelSerializermarks every field that takes part in aunique_togetherorUniqueConstraintas required unless it has a default or is nullable. ACharField/TextFieldwithblank=Truetherefore became required, even though Django would happily save it as an empty string. This broke a common pattern where a conditional constraint such ascondition=~Q(char_field='')deliberately excludes blank values from uniqueness.This PR adds a
blank=Truebranch toget_uniqueness_extra_kwargs, alongside the existingnull=Truebranch. Text fields that allow blank now getdefault='', so they stay optional while uniqueness is still validated against the empty string, exactly as the database would.Only
CharFieldandTextFieldsubclasses are affected. Other field types withblank=Truebut no default or null still fall through torequired=True, because the database would reject a missing value for those.Changes
rest_framework/serializers.py: setdefault=''for blank text fields in uniqueness constraints instead ofrequired=True.tests/test_validators.py: newBlankUniquenessTogetherModelandUniqueConstraintBlankModel(the latter mirrors the model from the issue) with tests covering:''unique_togethervalidation when a duplicate exists''allows repeated blank values and still rejects non-blank duplicatesdocs/api-guide/validators.md: document thatnull=Trueand blank text fields are not treated as required byModelSerializer.