简体   繁体   English

是否可以继承 Python 类型注解?

[英]Is it possible to inherit Python type annotations?

I'm learning a new tool called SQLModel , by Sebastian Ramirez (The FastAPI creator).我正在学习一种名为SQLModel的新工具,由 Sebastian Ramirez( FastAPI创建者)开发。

For basic CRUD operations in SQLModel, the docs teach you it's necessary to set up a model entity like this:对于 SQLModel 中的基本 CRUD 操作,文档告诉您有必要像这样设置一个 model 实体:

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 .我上面的示例将创建一个名为Room的 model,它是House的一部分。 This would have to be repeated for every new model class, meaning I can forget about putting multiple models in the same file.这必须对每个新的 model class 重复,这意味着我可以忘记将多个模型放在同一个文件中。

Lots of code for a little CRUD, right??一点点 CRUD 就需要很多代码,对吧??

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.因为我可能会在 90% 的时间内使用相同的 CRUD 设置(例如,我总是希望所有字段在更新时都是可编辑的,或者我总是只需要读取 ID 等),它得到了我想知道是否可以抽象上述内容,以便不必为每个数据库实体重复整个文件。

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?是否可以在 Python 中通过 inheritance 或其他方式传递字段和类型,这样我只需要编写一次上述代码的通用版本,而不必为每个 model 都写出来?

It appears you are using fastapi.看来您正在使用 fastapi。 If so, what about fastapi-crudrouter ?如果是这样, fastapi-crudrouter呢? It did the bulk of the work for me.它为我完成了大部分工作。 While googling for the fastapi-crudrouter link, I found another project FastAPIQuickCrud .在谷歌搜索 fastapi-crudrouter 链接时,我发现了另一个项目FastAPIQuickCrud Just skimming, but it seems to solve the same problem.只是略读,但似乎解决了同样的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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