datamodel-code-generator
datamodel-code-generator copied to clipboard
How to specify different base classes for different models?
Is your feature request related to a problem? Please describe.
Yes, I want to be able to specify different base classes for my generated models.
Describe the solution you'd like
We can specify the base class for all models using --base-class. For example, if my package is like this
my_package/base_classes.py
pyproject.toml
Then I can specify them as --base-class=my_package.base_classes.MyBaseClass, but this applies to all models, which is clearly undesirable. Ideally, we should be able to specify the base class for each model that is generated.
For example, we could have the flag --base-classes=base_classes.json, then base_classes.json would look like
{
"MyModel": "MyBaseClass",
"MyModel2": "MyBaseClass2",
}
Or something like that
Describe alternatives you've considered
The alternative could be to override the template and specify the base model depending on the name of the class, but the problem is that we can't import the base class in that way. The template only applies to a single model not the full module or Python file.
We could define the base class in the template, but this is really not ideal, because we want to reuse.
Similar https://github.com/koxudaxi/datamodel-code-generator/issues/2154
Similar #2154
@gaborbernat Ok, even if this is similar to #2154, why did close it? Has this been solved? If yes, can you provide the link to the PR that solves it? You closed it as completed.
The other issue is about not using enums for everything and using sometimes literals for certain fields, this is about using different base classes.
So, the only thing that is similar is that in both cases, sometimes, I want to use a different thing, but the things are different, a type hint and a base class, so the solution to these problems might be different. So, I don't know if it's a good idea to close this. I still need a solution to this problem (and the other problem too)!
Reopened @nbro10 feel free to put in a PR addressing this 👍
@gaborbernat Thanks. I'll see if I have the time to do it next weekend.
As for the configuration source, I'd prefer a table inside pyproject.toml instead of some JSON.