Sunday 27 August 2023

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



from Extending pydantic v2 model in Odoo

No comments:

Post a Comment