I am using the datamodel-code-generator to generate pydantic models from a JSON schema.
Here is the JSON schema used.
And the generated models after running the datamodel-code-generator.
# File: datamodel.py
from __future__ import annotations
from typing import List
from pydantic import BaseModel
class Record(BaseModel):
id: int
name: str
class Table(BaseModel):
records: List[Record]
class Globals(BaseModel):
table: Table
I've been trying to extend the generated classes with new attributes.
# File: extensions.py
import json
from datamodel import Table, Globals
class ExtendedTable(Table):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
print('ExtendedTable Constructor')
# Won't work because "ExtendedTable" object has no field "records_by_id"
self.records_by_id = {record.id: record for record in self.records}
class ExtendedGlobals(Globals):
def __init__(self, table: ExtendedTable):
super().__init__(table=table)
print('ExtendedGlobals Constructor')
if __name__ == '__main__':
records = '''
{
"table": {
"records": [{"id": 0, "name": "A"}, {"id": 1, "name": "B"}]
}
}
'''
content = json.loads(records)
# Both won't call ExtendedTable.__init__()
ExtendedGlobals(**content)
ExtendedGlobals.parse_obj(content)
ExtendedGlobals(table=ExtendedTable(**content['table']))
However, I haven't found a way to make the Globals class use the extended definition of the table. Also, simply adding new fields to the subclass does not seem to work.
Is there a way to extend these classes without having to modify the pydantic generated models? Or maybe another tool to generate Python code from JSON schema?