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,MaxLengthValidatorandMinLengthValidator, 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
makemigrationsto 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:
{ "number": ["Ensure this value is greater than or equal to <function small_funny_number at 0x7f0bdae20670>."], "text": ["Ensure this value has at least 42 characters (it has 1)."] } { "number": ["Ensure this value is less than or equal to <function large_funny_number at 0x7f6b15a830a0>."], "text": ["Ensure this value has at most 1337 characters (it has 9999)."] }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:
{ "number": ["Ensure this value is greater than or equal to <function small_funny_number at 0x7f0bdae20670>."], "text": ["Ensure this value has at least <function small_funny_number at 0x7f0bdae20670> characters."] } { "number": ["Ensure this value is less than or equal to <function large_funny_number at 0x7f6b15a830a0>."], "text": ["Ensure this value has at most <function large_funny_number at 0x7f6b15a830a0> characters."] }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'sMaxLengthValidatorinstead ofmax_length=for a CharField, but usingmin_value=andmax_value=for an IntegerField.So I suppose there would multiple changes here:
min/max_valueandmin/max_lengthkwargs 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