So I am working on my first project using SQLite and SQLModel as ORM. Creating and handling the first table in my database was easily structured: A function for each CRUD-Operation.
But now I have added a second table to my DB and am starting to think about structure a bit. Essentially I want to do the same thing for all of my tables: Add an entry, edit it, get one or all entries and delete the entry. So do I add those functions for the CRUD operations again for each entry? Or do I create "general-purpose" functions for those operations? I could do this something like this:
def create_entry(table: SQLModel, _id: int, **kwargs):
with Session(engine) as session:
...
I don't like the use of **kwargs though. So maybe I would create extra dataclasses something like this:
from dataclasses import dataclass
@dataclass
class Update():
id: int
@dataclass
class HeroUpdate(Update):
name: Optional[str]
age: Optional[str]
@dataclass
class Teamupdate(Update):
teamname: Optional[str]
def update_entry(table: SQLModel, values: Update):
with Session(engine) as session:
...
Or should I maybe create a class which handles the transactions (while still using the dataclasses to model the field?)?
class BaseTransactions:
def __init__(table: SQLModel):
self.table = table
def create(values: Create)
with Session(engine) as session:
...
So to sum up my question: Is there a standard, pythonic way to structure code for database transactions when using an ORM?