Best way to add nested model with relationship in Create #1116
Replies: 1 comment
-
Hi, @jonyscathe I tried your solution and it also worked for me, but there is still a thing to consider. At the first line of a path operation, when fastapi validation is finished and before Hero itself has a I am not sure where, but I have an intuition, that this inconsistency could cause a bug down a stream. I was thinking to write a Another option is to not perform any automatic conversions and write all by hands. This approach is recommended in DRF, for example:
At last, what is a need to perform an object creation in path operation code? This data is more likely to be passed to some service containing a business logic, which handles connected objects creation. So for myself I would either call pop teams info and call PS: another catch - if you pass a foreign key of non-existing key while creating a book - it will return 500 instead of 400 with a fancy error description, because 666 is still a valid int, although team with id 666 does not exist. |
Beta Was this translation helpful? Give feedback.
-
First Check
Commit to Help
Example Code
Description
I am trying to work out what the best method is for creating SQLModel objects with nested objects beneath them.
The example code in the tutorial shows reading data (such as with HeroPublicWithTeam) but not creating data.
My code above seems to work ok - it is just the
Models with Relationships in FastAPI
code with the HeroCreate class modified to optionally allow a Team to also be created within the same API call - and team_id moved from HeroBase to Hero as it doesn't make sense for HeroCreate to have a team and a team_id in it.Is this the best way to achieve this?
Or am I missing a simpler way to do this that doesn't involve an AfterValidator which seems like an odd way to achieve this?
Just having
team: TeamCreate | None = None
leads to'TeamCreate' object has no attribute '_sa_instance_state'
Just having
team: Team | None = None
means thatid
is part of the API for creating a team within the hero creation leading to the inevitablesqlalchemy.exc.IntegrityError: (psycopg.errors.UniqueViolation) duplicate key value violates unique constraint "team_pkey"
Operating System
Linux
Operating System Details
python-slim docker container
SQLModel Version
0.0.22
Python Version
3.12.6
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions