Allow custom model config

This commit is contained in:
Joshua Kifer
2021-07-24 11:43:48 -07:00
parent 9bf2bdf00e
commit 29761999e7
2 changed files with 23 additions and 1 deletions

View File

@ -552,7 +552,13 @@ class ModelMetaclass(pydantic.main.ModelMetaclass):
:param attrs: class namespace :param attrs: class namespace
:type attrs: Dict :type attrs: Dict
""" """
if "Config" in attrs:
class Config(attrs["Config"], get_pydantic_base_orm_config()):
pass
attrs["Config"] = Config
else:
attrs["Config"] = get_pydantic_base_orm_config() attrs["Config"] = get_pydantic_base_orm_config()
attrs["__name__"] = name attrs["__name__"] = name
attrs, model_fields = extract_annotations_and_default_vals(attrs) attrs, model_fields = extract_annotations_and_default_vals(attrs)
for base in reversed(bases): for base in reversed(bases):

View File

@ -150,6 +150,12 @@ class Bus2(Car2):
max_persons: int = ormar.Integer() max_persons: int = ormar.Integer()
class ImmutablePerson(Person):
class Config:
allow_mutation = False
validate_assignment = False
@pytest.fixture(autouse=True, scope="module") @pytest.fixture(autouse=True, scope="module")
def create_test_database(): def create_test_database():
metadata.create_all(engine) metadata.create_all(engine)
@ -495,3 +501,13 @@ async def test_inheritance_with_multi_relation():
assert len(unicorns) == 2 assert len(unicorns) == 2
assert unicorns[1].name == "Unicorn 2" assert unicorns[1].name == "Unicorn 2"
assert len(unicorns[1].co_owners) == 1 assert len(unicorns[1].co_owners) == 1
def test_custom_config():
# Custom config inherits defaults
assert getattr(ImmutablePerson.__config__, "orm_mode") == True
# Custom config can override defaults
assert getattr(ImmutablePerson.__config__, "validate_assignment") == False
sam = ImmutablePerson(name="Sam")
with pytest.raises(TypeError):
sam.name = "Not Sam"