eran helzer
eran helzer

Reputation: 155

How to pass pydantic create_model config and base arguments

It seems that pydantic does not allow passing both base and config arguments to create_model function, to avoid confusion.

What I tried to do is:

from pydantic import BaseModel, create_model

class Config:
    orm_mode = True

E = create_model('E', name='name', __base__=BaseModel)

B = create_model('B', age=1, __base__=E, __config__=Config)

Using classes this is very simple:

class E(BaseModel):
    name = 'name'

class B(E):
    age = 18

    class Config:
        orm_mode = True

Is there any way to do this using create_model?

Upvotes: 8

Views: 3621

Answers (1)

dwich
dwich

Reputation: 1725

I took a look at Pydantic tests - test_create_model.py and found a simple test that demonstrates how to use Config and Base together:

def test_config_and_base():
    with pytest.raises(errors.ConfigError):
        create_model('FooModel', __config__=BaseModel.Config, __base__=BaseModel)

There are also other tests that demonstrate how to use Config class together with create_model()

def test_custom_config():
    class Config:
        fields = {'foo': 'api-foo-field'}

    model = create_model('FooModel', foo=(int, ...), __config__=Config)
    assert model(**{'api-foo-field': '987'}).foo == 987
    assert issubclass(model.__config__, BaseModel.Config)
    with pytest.raises(ValidationError):
        model(foo=654)


def test_custom_config_inherits():
    class Config(BaseModel.Config):
        fields = {'foo': 'api-foo-field'}

    model = create_model('FooModel', foo=(int, ...), __config__=Config)
    assert model(**{'api-foo-field': '987'}).foo == 987
    assert issubclass(model.__config__, BaseModel.Config)
    with pytest.raises(ValidationError):
        model(foo=654)


def test_custom_config_extras():
    class Config(BaseModel.Config):
        extra = Extra.forbid

    model = create_model('FooModel', foo=(int, ...), __config__=Config)
    assert model(foo=654)
    with pytest.raises(ValidationError):
        model(bar=654)

Upvotes: 0

Related Questions