datamodel-code-generator icon indicating copy to clipboard operation
datamodel-code-generator copied to clipboard

How to specify different base classes for different models?

Open nbro10 opened this issue 1 year ago • 6 comments
trafficstars

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.

nbro10 avatar Oct 25 '24 15:10 nbro10

Similar https://github.com/koxudaxi/datamodel-code-generator/issues/2154

nbro10 avatar Jan 01 '25 17:01 nbro10

Similar #2154

gaborbernat avatar Feb 06 '25 20:02 gaborbernat

@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)!

nbro10 avatar Feb 07 '25 10:02 nbro10

Reopened @nbro10 feel free to put in a PR addressing this 👍

gaborbernat avatar Feb 11 '25 17:02 gaborbernat

@gaborbernat Thanks. I'll see if I have the time to do it next weekend.

nbro10 avatar Feb 11 '25 21:02 nbro10

As for the configuration source, I'd prefer a table inside pyproject.toml instead of some JSON.

gaborbernat avatar Feb 11 '25 21:02 gaborbernat