Validation on many to many field when default=None #9790
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.
Note: Before submitting a code change, please review our contributing guidelines.
Description
Hi!
First of all, thank you for the library, it's very useful for my work!
While working on a project, I got a 500 error in production due to a configuration error on my part (copy-paste 🤦♂️): when using a
PrimaryKeySerializer
on a ManyToMany field and settingdefault=None
like this:It crashes at runtime with the following exception when no value is provided for
targets
field:Now it seems simple and intuitive, but in production, with thousands of lines, dozens of serializers, and hundreds of fields, it took me a long time to figure out what the problem was.
To prevent errors in production, I added a new validation in the
get_fields()
method with a super descriptive message indicating a solution (I also added some tests to check this new behavior).I couldn't find an earlier place to perform the validation, but this change allows the validation to run for other methods such as
create()
orupdate()
. If you have a better place where the code block could be moved, please let me know, and I'll make the necessary adjustments.Finally, since this is my first time collaborating on the project, I added some help to the contributing.md file to explain a few things, such as the
-s
parameter in pytests, which allows you to obtain the output during testing, ordjango.test.TestCase
inheritance so you can use the Django DB. If you think it shouldn't be there, or you don't like the format, let me know and I can make the changes.Thanks and best regards!