在FastAPI中,我遇到了类似的情况:

models.py

class MachineGroups(Base):
    __tablename__ = 'MachineGroups'

    MachineGroupsId = Column(NVARCHAR(25), primary_key=True)
    Description = Column(NVARCHAR(255))


class Machines(Base):
    __tablename__ = 'Machines'

    MachinesId = Column(NVARCHAR(50), primary_key=True)
    Description = Column(NVARCHAR(255))
    MachineGroupsId = Column(NVARCHAR(25), ForeignKey("MachineGroups.MachineGroupsId", ondelete="SET NULL"), nullable=True)

    group = relationship("MachineGroups")

schemas.py

class MachineGroups(BaseModel):
    MachineGroupsId: str
    Description: str

    class Config:
        orm_mode = True


class Machines(BaseModel):
    MachinesId: str
    Description: str
    MachineGroupsId: str = None
    group: Optional[MachineGroups] = None

    class Config:
        orm_mode = True

在控制器中,我有一个如下创建的函数:

controller.py

@app.get(
    "/machines",
    response_model=List[machine_schemas.Machines],
    response_model_exclude={'group'}
)
def get_machines(db: Session = Depends(get_db)):
    return db.query(machine_models.Machines).all()

我希望能够直接从API调用中设置decorator中的response_model_exclude字段值.实际上,我希望在函数上有一个查询参数,该参数允许我获取外键信息或不获取外键信息.

为避免出现这种情况:

@app.get(
    "/machines",
    response_model=List[machine_schemas.Machines],
    response_model_exclude={'group'}
)
def get_machines(db: Session = Depends(get_db)):
    return db.query(machine_models.Machines).all()

@app.get(
    "/machines/all",
    response_model=List[machine_schemas.Machines],
)
def get_machines_all(db: Session = Depends(get_db)):
    return db.query(machine_models.Machines).all()

有可能做到这一点吗?

非常感谢.

推荐答案

我通过创建一个自定义JSONResponse并使用jsonable_encoder函数排除外键字段,解决了这个问题.

@app.get(
    "/machines/all",
    response_model=List[machine_schemas.Machines],
)
def get_machines_all(get_foreign_keys: bool = True, db: Session = Depends(get_db)):
    machines = db.query(machine_models.Machines).all()
    if get_foreign_keys:
        return machines
    else:
        return JSONResponse(jsonable_encoder(machines, exclude={'group'}))

Python-3.x相关问答推荐

TypeError:&Quot;Value&Quot;参数必须是标量、Dict或Series,但您传递了&Quot;Index&Quot;

安装grpcio时出现错误DeproationWarning:pkg_resource

如何从选定的html内容中获取所需的文本

无法导入名称';核心';来自部分初始化的模块';tensorflow_datasets';(很可能是由于循环导入)

在不使用 split 函数的情况下从字符串中分割逗号(','),句号('.')和空格(' '),将字符串的单词附加到列表中

在特定条件下从 DataFrame 中提取特定组

ImportError:抓取数据后找不到 html5lib

将 pandas Timestamp() 转换为 datetime.datetime() 以支持 peewee DateTimeField()

多进程:两个进程,一起杀死

使用 OpenCV 从图像中减go 一条线

pysftp vs. Paramiko

tkinter TclError:错误的文件类型使用 askopenfilename

为什么在 Python 3 中实例的 __dict__ 的大小要小得多?

新项目:Python 2 还是 Python 3?

Python 2 与 Python 3 - urllib 格式

如何对字典的函数输出列表进行单元测试?

Python 无法处理以 0 开头的数字字符串.为什么?

在 Meta 中创建具有动态模型的通用序列化程序

有没有办法在多个线程中使用 asyncio.Queue ?

在 PyCharm 中配置解释器:请使用不同的 SDK 名称