Search code examples
pythonodoopydanticodoo-16

Extending pydantic v2 model in Odoo


Odoo 16, Pydantic v2, extendable-pydantic 1.1.0

Use case:

  • Main module with pydantic model MainModel
  • One (or more) add-on modules which are dependant on Main module and extend MainModel with new fields
  • When only main module is active, the MainModel should have only field_a and field_b
  • When Addon module A(...) is installed, the MainModel should have an additional field field_c (...)

Simplified dummy implemenation :

Main module , main.py

from extendable_pydantic import ExtendableModelMeta
from pydantic import BaseModel
from extendable import context, registry

class MainModel(BaseModel, metaclass=ExtendableModelMeta):
    field_a: str
    field_b: int
    
_registry = registry.ExtendableClassesRegistry()
context.extendable_registry.set(_registry)
_registry.init_registry()

... fastApi endpoints that utilize MainModel below ...

Addon module A, extended_main.py

from odoo.addons.main_module.modules.main import MainModel

class ExtendedMainModel(MainModel, extends=MainModel):
    field_c: int

The result is that ExtendedMainModel is ignored and MainModel has only field_a and field_b


Solution

  • You need to initialize the registry after declaring all classes (in module A) as stated in the Extendable project description:

    To finalyse the process, we need to instruct the runtime that all our class declarations are done by building the final class definitions and making it available into the current execution context.