django-ninja
django-ninja copied to clipboard
Documentation Issue - Optional field declarations incompatible with pydantic 2
The documentation contains several examples of declaring optional fields within a Schema by simply providing a default value. However pydantic2 requires these fields to be explicitly typed as Optional
Instances I've found:
- Responses - Code comment explicitly provides old method
- Tutorial pt 3
- CRUD
Hi @sumebrius could you show on pydantic doc where they require this ?
Generally it works, but just not very type-accurate
Hi @sumebrius could you show on pydantic doc where they require this ?
Generally it works, but just not very type-accurate
Not from the documentation, but the issue have been discussed in part here; https://github.com/pydantic/pydantic/issues/6546.
Hmm... so checking through the pydantic docs, I can't seem to find much around optional/nullable fields - aside from this section in the migration guide to v2 warning that the logic has changed (and related to the issue @TobiasEdqvist linked.)
Doing some digging around in the docs, and a bit of experimentation myself - I think I have originally misunderstood the pydantic2 requirements/behaviour. It looks like:
-
field: str = None
- If provided, must be a string (cannot beNone
/null
). May not be provided in the payload, in which casefield
is set toNone
. There are actually several examples of this in the pydantic2 docs, but they mostly look like they were never updated from the old version docs) -
field: Optional[str]
- Must be provided, but may beNone
. -
field: Optional[str] = None
- May or may not be provided. May beNone
. Set toNone
if not provided.
The examples I referenced in the ninja docs aren't necessarily incorrect, but they do have implications that could lead new users to fall into pitfalls (like the one I did when upgrading to v1.0 :smiling_face_with_tear:) - I'd argue that one of the last 2 options would be "best practice" to encourage in the docs.
I'd be happy to submit a PR adding a small section on optional fields to the Schema docs, if you agree with the above.