Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to inherit Python type annotations?

I'm learning a new tool called SQLModel, by Sebastian Ramirez (The FastAPI creator).

For basic CRUD operations in SQLModel, the docs teach you it's necessary to set up a model entity like this:

from typing import Optional, List
from sqlmodel import Field, SQLModel, Relationship


class RoomBase(SQLModel):
    name: str
    is_ensuite: bool
    current_occupants: Optional[List[str]]
    house_id: Optional[int] = Field(default=None, foreign_key="house.id")

class Room(RoomBase, table=True):
    id: Optional[int] = Field(default=None, primary_key=True)
    house: Optional["House"] = Relationship(back_populates="rooms")

class RoomCreate(RoomBase):
    pass

class RoomRead(RoomBase):
    id: int

class RoomUpdate(SQLModel):
    name: Optional[str] = None
    is_ensuite: Optional[bool] = None
    current_occupants: Optional[List[str]] = None
    house_id: Optional[int] = None

My example above will create a model called Room, which is part of a House. This would have to be repeated for every new model class, meaning I can forget about putting multiple models in the same file.

Lots of code for a little CRUD, right!?

Since it's likely that I will use the same CRUD setup 90% of the time (e.g. I will always want all the fields to be editable on an update, or I will always only need the ID for a read, etc.), it got me wondering whether the above could be abstracted, so that whole file didn't have to be repeated for EVERY SINGLE database entity.

Is it possible in Python to pass in fields and types by means of inheritance or otherwise, such that I would only need to write a generic version of the above code once, rather than having to write it all out for every model?

like image 585
John Kealy Avatar asked Feb 26 '26 17:02

John Kealy


1 Answers

It appears you are using fastapi. If so, what about fastapi-crudrouter? It did the bulk of the work for me. While googling for the fastapi-crudrouter link, I found another project FastAPIQuickCrud. Just skimming, but it seems to solve the same problem.

like image 86
Frustrated Avatar answered Feb 28 '26 08:02

Frustrated



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!