Automatically detect models null=True, blank=True, unique=True and set serializers allow_blank=False #8841
Unanswered
kiraware
asked this question in
Ideas & Suggestions
Replies: 1 comment 1 reply
-
can you help us to dig it further and figure out some possible approach for this? |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.
Uh oh!
There was an error while loading. Please reload this page.
-
TL;DR
If models
blank=True
,null=True
, andunique=True
then set serializersallow_blank=False
The default
serializers.ModelSerializer
class provide very close to models field definition. This feature is very nice, but it came into problem if we set models field withblank=True
,null=True
,unique=True
and the serializer will setallow_blank=True
,allow_null=True
,required=False
. The problem with this is when we create or update with blank, the serializer will save it with empty string""
, for the first time it's not a problem to the database since no one field in database contain empty string""
, but if we create or update another field with blank again, the database will raiseIntegrityError
due to empty string""
which is originally caused byunique=True
.Suppose we have models
And serializers
We have this field set
Here is the summary of model and serializer default behaviour with logical table
The problem is in
field5
andfield7
, due to theirunique
is set toTrue
, saving the blank or empty string""
into database for the first time is not a problem, but not for second time. The database will raise IntegrityError due to UNIQUE constraint failed by empty string""
.The case with
field5
is unlikely to be happen in real world, and if this really happen, we couldn't fix it by setallow_blank
toFalse
andallow_null
toTrue
. Due to models definition set thenull
toFalse
, hence we couldn't fix itThe case with
field7
is likely to be happen, and if this really happen we can fix it by setallow_blank
toFalse
. Therefore the serializers won't accept blank or empty string""
, so that the database raisingIntegrityError
is unlikely to be happenAfter all, the developer could fix the
field7
case by explicitly setallow_blank=False
,allow_null=True
,required=False
either inextra_kwargs
Meta field or in serializer definition. But i think it would be nice if DRF automatically detect case infield7
and set theallow_blank
toFalse
so that the developer don't have to set it manuallyThanks for your attention!
Beta Was this translation helpful? Give feedback.
All reactions