Replies: 1 comment 4 replies
-
I'm not sure whether I understood your requirement correctly, but I guess you can have a look at if this is what you need from sqlmodel import SQLModel, Field
class Hero(SQLModel, table=True):
hero_id: int | None = Field(default=None, primary_key=True)
hero_name: str
hero_avatar: str
item = Hero(hero_id=1, hero_name="John", hero_avatar="https://example.com/avatar.jpg")
item_class = str(type(item)).strip("<").strip(">").strip("'").rsplit(".")[-1]
item_id = getattr(item, f"{item_class.lower()}_id")
print(item_id) |
Beta Was this translation helpful? Give feedback.
4 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
First Check
Commit to Help
Example Code
Description
Consider the above sample code. I would call
create_static_data()
in the lifespan module of fastapi.I'm looking for a way to declaratively define some static data at the beginning of each run.
It aims to be a more of a MERGE statement rather than an INSERT if blank situation. If it exists and is different, update it. If it doesn't exist, create it. If it exists but is not in the new list, delete it.
If at any time anyone changes the code in
create_static_data()
, it should change the static data in the database too.In the above codebase, I have a sample
_sync_static_data()
which works with the Items model, given that the primary key is justid
. In an ideal world, all models can just haveid
as their primary key and this function would work.However, if you uncomment the
heroes
andteams
declarations, the_sync_static_data()
code will error as their id's arehero_id
andteam_id
respectively.What's a better implementation to resolve this? Possible Solutions:
_sync_static_data()
more seamlessly and natively?Operating System
Linux, Windows
Operating System Details
WSL
SQLModel Version
0.0.18
Python Version
3.10.5
Additional Context
No response
Beta Was this translation helpful? Give feedback.
All reactions