inherit choices validators and class validators for fields in generated pydantic models

This commit is contained in:
collerek
2021-10-11 16:22:50 +02:00
parent f6458be157
commit 9559c0f7f6
6 changed files with 46 additions and 25 deletions

View File

@ -4,11 +4,8 @@ from fastapi import FastAPI
from starlette.testclient import TestClient
from tests.settings import DATABASE_URL
from tests.test_inheritance_and_pydantic_generation.test_geting_the_pydantic_models import (
from tests.test_inheritance_and_pydantic_generation.test_geting_pydantic_models import (
Category,
Item,
MutualA,
MutualB,
SelfRef,
database,
metadata,
@ -53,7 +50,9 @@ app.post("/categories/", response_model=Category)(create_category)
response_model=SelfRef.get_pydantic(exclude={"parent", "children__name"}),
)
async def create_selfref(
selfref: SelfRef.get_pydantic(exclude={"children__name"}), # type: ignore
selfref: SelfRef.get_pydantic( # type: ignore
exclude={"children__name"} # noqa: F821
),
):
selfr = SelfRef(**selfref.dict())
await selfr.save()

View File

@ -5,7 +5,6 @@ import pydantic
import pytest
import sqlalchemy
from pydantic import ValidationError
from pydantic.class_validators import make_generic_validator
import ormar
@ -44,26 +43,14 @@ class ModelExample(ormar.Model):
raise ValueError("must contain a space")
return v
def validate_str_field(cls, v):
if " " not in v:
raise ValueError("must contain a space")
return v
def validate_choices(cls, v):
if v not in list(EnumExample):
raise ValueError(f"{v} is not in allowed choices: {list(EnumExample)}")
return v
@pydantic.validator("str_field")
def validate_str_field2(cls, v):
if " " not in v:
raise ValueError("must contain a space")
return v
ModelExampleCreate = ModelExample.get_pydantic(exclude={"id"})
ModelExampleCreate.__fields__["str_field"].validators.append(
make_generic_validator(validate_str_field)
)
ModelExampleCreate.__fields__["enum_field"].validators.append(
make_generic_validator(validate_choices)
)
def test_ormar_validator():