[bug] default_factory
called twice when parse input by FastAPI/route
#608
dacrystal
started this conversation in
Show and tell
Replies: 2 comments 2 replies
-
Just a note, that I guess that with the multiple models pattern this does not typically happen, because the *Create model does not include fields with factories, but typically the db model does. https://sqlmodel.tiangolo.com/tutorial/fastapi/multiple-models/ Sure would be nice to fix anyhow. |
Beta Was this translation helpful? Give feedback.
1 reply
-
@antont
Here is a more comprehensive example: from typing import List, Optional
from sqlmodel import Field, SQLModel
from pydantic import parse_obj_as
def gen_id():
gen_id.i += 1
print(f"gen_id called. id={gen_id.i}")
return gen_id.i
gen_id.i = 0
class HeroBase(SQLModel):
name: str = Field(index=True)
secret_name: str
age: Optional[int] = Field(default=None, index=True)
class Hero(HeroBase, table=True):
id: int = Field(primary_key=True, default_factory=gen_id)
class HeroCreate(HeroBase):
pass
hero_create = HeroCreate(name="Deadpond", secret_name="Dive Wilson")
hero_create_list = [
HeroCreate(name="Spider-Boy", secret_name="Pedro Parqueador"),
HeroCreate(name="Deadpond", secret_name="Dive Wilson")]
# This work, but...
hero_parse_obj = Hero.parse_obj(hero_create)
gen_id.i = 0
# default_factory/validations called twice
hero_validate = Hero.validate({"name": "Deadpond",
"secret_name": "Dive Wilson"})
# default_factory/validations called twice
gen_id.i = 0
hero_from_orm = Hero.from_orm(hero_create)
# default_factory/validations called twice
gen_id.i = 0
hero_list = parse_obj_as(List[Hero], hero_create_list)
assert hero_parse_obj.id == 1
assert hero_validate.id == 1
assert hero_from_orm.id == 1
assert hero_list[0].id == 1 Or I might be doing it wrongly. |
Beta Was this translation helpful? Give feedback.
1 reply
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
Current Behavior (example Code):
Expected Behavior
default_factor
andvalidations
should run once.Root cause
The issue is that
validation_model
called twice directly inL589
and indirectly inL592
(init)https://github.com/tiangolo/sqlmodel/blob/43a689d369f52b72aac60efd71111aba7d84714d/sqlmodel/main.py#L583-L605
in
__init__
:https://github.com/tiangolo/sqlmodel/blob/43a689d369f52b72aac60efd71111aba7d84714d/sqlmodel/main.py#L498-L498
Beta Was this translation helpful? Give feedback.
All reactions