How to use local namespace with model_rebuild in Pydantic V2

98 Views Asked by At

I'm using Pydantic with SQLModel in an app in which I dynamically generate models for different SQLModel metaclass instances (each one linked to a different database). With Pydantic v1 I was using update_forward_refs with a localns parameter, but I am unable to find the equivalent in Pydantic v2. I really need to use localns since models are bound to a SQLModel subclass.

My classes were defined like so :

def generate_user_model(sqlmodel_class, repository):
    class UserModel(sqlmodel_class, table=True):
        id: Optional[int] = Field(default=None, primary_key=True)
        name: str

    UserModel.__module__ = sqlmodel_class.__name__
    repository['UserModel'] = UserModel

And used like so.

class DBMetaclass:
    def __init__(self, sqlmodel_class):
        self.sqlmodel_class = sqlmodel_class
        self.repository = {}

    def generate_models():
        generate_user_model(self.sqlmodel_class)
        # other model defs...

        for cls in self.repository.values():
            cls.update_forward_refs(**self.repository)
    

Since some models are referencing each other but are dynamically generated I need to use update_forward_refs on each generate model, using only local namespace corresponding to the current SQLModel subclass.

I would like to migrate to Pydantic V2 but the model_rebuild that replaces update_forward_refs method does not take localns parameter. How should I proceed?

0

There are 0 best solutions below