Open YYYasin19 opened 11 months ago
@YYYasin19 I'm sorry for my late reply.
and a mapping between the ID fields and some more descriptive names was used (to make them more readable).
How do you use the mapping data when generating a model? I can't see the logic to inject it.
Hi,
I just pass the --aliases mapping.json
option to the CLI interface or a dict to the Python interface.
I'm not sure if I'm using this incorrectly, since the bug should be very general, i.e. everyone using an alias mapping should be affected by it, right?
I am affected by this, datamodel-code-generator
is generating Models matching the same name/case as field names, which is causing Pydantic validation issues when their type contraints are Optional[T] = None
. I am not using any annotations or aliases.
I have the same issues as described by @nwithan8 above; although haven't looked into the code deeper.
It is essentially an issue with name collisions between field and type annotation, as described here: https://docs.pydantic.dev/2.8/errors/validation_errors/#none_required
Hi @koxudaxi. We're also experiencing the same issue as @nwithan8. In our OpenAPI spec, if a nested object is named with a capital letter e.g. Foo
then the generator creates a class called Foo
and references it in the base model as Foo: Optional[Foo] = None
- this triggers the Pydantic Input should be None
error as mentioned previously and linked in the previous comment by @cpnat.
Is there any simple way to solve or work around this? We can't exactly change the naming of the fields in the OpenAPI spec. One possibility I can think of is if there was a way to add a custom prefix/suffix to all generated classes to avoid collision with the field name.
Describe the bug I have used
datamodel-code-generator
with a custom mapping to create a Pydantic v2 model. Doing that resulted in field names having the same name as other models which messes up validation for Optional fields. I believe the bug (?) is, independent of specific settings, present for all cases where one might use optional fields and a mapping.To Reproduce The JSON Schema roughly looks like this
and a mapping between the ID fields and some more descriptive names was used (to make them more readable).
This resulted in a code that looks like this
where the problem is that the field should not be called
Model2
like the class is.Used commandline:
Expected behavior The issue is fixed by making sure that the field names aren't the same as the other model names. I achieved this temporarily by modifying the
.jinja2
template like thisVersion:
3.10
0.22.0
Additional context Is there a way to modify this consistently? Passing the
custom_template_dir
argument didn't seem to work for me. If this is indeed a bug, I'm happy to provide a PR if someone can tell me where the field names are created! :)