Skip to content

Conversation

fazeelghafoor
Copy link

Fixes #1153 Add support for union type field in model schema

@fazeelghafoor
Copy link
Author

@vitalik can you please review and let me know if anything needs to be modified. I think this is a partial fix to #1153 but I felt like at least add support for UnionTypes.

@fazeelghafoor fazeelghafoor changed the title add union type and subtypes check in schema model signature Add union type and subtypes check in schema model signature Jul 29, 2024
@vitalik
Copy link
Owner

vitalik commented Aug 10, 2024

Could you also add some unit tests for this ?

@Mapiarz
Copy link

Mapiarz commented Jan 8, 2025

@fazeelghafoor Thanks for this fix! Any chance to see the extra coverage on this? It's a pity this fix is stuck and it's really important imho.

Copy link

@dan-blanchard dan-blanchard left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I obviously don't have the permissions to really review this, but this is currently a big blocker for my team to update to the latest version of django-ninja. Even when using some_field: Optional[SomeSchema]-style annotations with pydantic 2.0, nested schemas do not work. With this PR, they do.

if get_origin(model) in UNION_TYPES:
# If the model is a union type, process each type in the union
for arg in get_args(model):
if type(arg) is None:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I applied this patch locally to test things out and noticed that this is flipped.

Suggested change
if type(arg) is None:
if arg is type(None):

arg will be a type, and we want to check if it's NoneType.

# check union types
if get_origin(annotation_or_field) in UNION_TYPES:
for arg in get_args(annotation_or_field):
if type(arg) is None:

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
if type(arg) is None:
if arg is type(None):

@dan-blanchard
Copy link

I tried to pick this up in #1512

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging this pull request may close these issues.

[BUG] Using pydantic.Json[SomeModel] in a query param fails
4 participants