Support callable minimum and maximum integer values and string lengths #8833
Unanswered
Lucidiot
asked this question in
Potential Issue
Replies: 0 comments
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.
-
The Django docs for the validators mention that for
MaxValueValidator
,MinValueValidator
,MaxLengthValidator
andMinLengthValidator
, the limit may be a callable. So in theory, it should be possible to do this:Note that you cannot use lambdas here, as the callable must have a name for Django's
makemigrations
to work.Now, put that in a serializer and into a POST API view:
If you make some API requests with invalid values, you will get the following error messages:
When you declare the serializer fields yourself, the messages are slightly different. The docs for CharField and IntegerField do not mention support for callable min/max values and min/max lengths, but you can still use them.
You will then get these messages:
This time, the CharField is also affected, and does not display the number of characters that the user sent as
(it has X)
. I guess that the ModelSerializer's automatic serializer field creation generates the two fields differently, using Django'sMaxLengthValidator
instead ofmax_length=
for a CharField, but usingmin_value=
andmax_value=
for an IntegerField.So I suppose there would multiple changes here:
min/max_value
andmin/max_length
kwargs into validators. Maybe just leave that up to Django's validators, since they already generate validation errors with similar messages?validators=[]
in the ModelSerializer's automatic field generationThoughts?
Beta Was this translation helpful? Give feedback.
All reactions