简体   繁体   中英

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 (eg 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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM