wip
This commit is contained in:
parent
4be274d9e2
commit
c238b9d757
21 changed files with 219 additions and 184 deletions
0
learn_sql_model/models/__init__.py
Normal file
0
learn_sql_model/models/__init__.py
Normal file
46
learn_sql_model/models/fast_model.py
Normal file
46
learn_sql_model/models/fast_model.py
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
from typing import Optional, TYPE_CHECKING
|
||||
|
||||
from sqlmodel import SQLModel, select
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from learn_sql_model.config import Config
|
||||
|
||||
|
||||
class FastModel(SQLModel):
|
||||
def pre_post(self) -> None:
|
||||
"""run before post"""
|
||||
|
||||
def pre_delete(self) -> None:
|
||||
"""run before delete"""
|
||||
|
||||
@classmethod
|
||||
def pre_get(self) -> None:
|
||||
"""run before get"""
|
||||
|
||||
def post(self, config: "Config" = None) -> None:
|
||||
if config is None:
|
||||
from learn_sql_model.config import get_config
|
||||
|
||||
config = get_config()
|
||||
|
||||
self.pre_post()
|
||||
|
||||
with config.session as session:
|
||||
session.add(self)
|
||||
session.commit()
|
||||
|
||||
@classmethod
|
||||
def get(
|
||||
self, item_id: int = None, config: "Config" = None
|
||||
) -> Optional["FastModel"]:
|
||||
if config is None:
|
||||
from learn_sql_model.config import get_config
|
||||
|
||||
config = get_config()
|
||||
|
||||
self.pre_get()
|
||||
|
||||
with config.session as session:
|
||||
if item_id is None:
|
||||
return session.exec(select(self)).all()
|
||||
return session.exec(select(self).where(self.id == item_id)).one()
|
||||
13
learn_sql_model/models/hero.py
Normal file
13
learn_sql_model/models/hero.py
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
from typing import Optional
|
||||
|
||||
from sqlmodel import Field
|
||||
|
||||
from learn_sql_model.models.fast_model import FastModel
|
||||
|
||||
|
||||
class Hero(FastModel, table=True):
|
||||
id: Optional[int] = Field(default=None, primary_key=True)
|
||||
name: str
|
||||
secret_name: str
|
||||
age: Optional[int] = None
|
||||
shoe_size: Optional[int] = None
|
||||
16
learn_sql_model/models/pet.py
Normal file
16
learn_sql_model/models/pet.py
Normal file
|
|
@ -0,0 +1,16 @@
|
|||
from typing import Optional
|
||||
|
||||
from sqlmodel import Field
|
||||
|
||||
from learn_sql_model.models.fast_model import FastModel
|
||||
|
||||
|
||||
class Pet(FastModel, table=True):
|
||||
id: Optional[int] = Field(default=None, primary_key=True)
|
||||
name: str = "Jim"
|
||||
|
||||
|
||||
# age: Optional[int] = None
|
||||
|
||||
# hero_id: int = Field(default=None, foreign_key="hero.id")
|
||||
# hero: Optional[Hero] = Relationship(back_populates="pets")
|
||||
Loading…
Add table
Add a link
Reference in a new issue