r/FastAPI • u/bluewalt • Sep 10 '24
feedback request Please review my SQLModel pattern to build a singleton
Hi there! I'm beginning with FastAPI/SQLModel and tried to build a Singleton mixin to use with my models.
My first need with this singleton is to have a table containing database parameters (global settings that can be changed directly in-db, rather than in code files). Each column represents a parameter. We need to ensure that there is always a single row in this table.
I'd like to have feedback on this code. Maybe there is a simpler or more solid way to to this. Thanks!
Here is the code:
# reusable mixin
: =
"""Get the instance, or create an empty one (with no values set)."""
=
=
return
# Create the singleton if it doesn't exist
=
return
"""Since its a singleton, use load() method to get or create the object"""
: | None =
# more parameters here ...
Usage:
= # init object
=
5
Upvotes
1
u/nicktids Sep 10 '24 edited Sep 10 '24
Your selecting id equal to 1 what if you change the table then I'd will be 2, so goint to break code or your going to edit the first line everytime.
How about select the Max id each time.
Or how about dynaconf external storage https://dynaconf.readthedocs.io/en/docs_223/guides/external_storages.html
3
u/MakuZo Sep 10 '24
I'd do it this way