Python SQLAlchemy中外键的外键检查

Python SQLAlchemy中外键的外键检查,python,sqlalchemy,Python,Sqlalchemy,我有以下3种sql alchemy(sqla)模型: camera\u id是rtspserverendpoint表的外键,site\u id是camera表的外键 当用户想要添加新的rtspserverendpoint记录时,他会发出HTTP请求,例如: 发布站点//摄像头//rtspserverendpoint 在添加新的rtspserverendpoint之前,我想确保和是一致的,作为一种安全性。我可能可以单独查询以检查,例如: check_record_exist = db.sessio

我有以下3种sql alchemy(sqla)模型:

camera\u id
rtspserverendpoint
表的外键,
site\u id
是camera表的外键

当用户想要添加新的
rtspserverendpoint
记录时,他会发出HTTP请求,例如: 发布站点//摄像头//rtspserverendpoint

在添加新的
rtspserverendpoint
之前,我想确保
是一致的,作为一种安全性。我可能可以单独查询以检查,例如:

check_record_exist = db.session.query(Camera).filter(Camera.site_id == site_id).first()
if not check_record_exist:
    raise ("No such camera with this site_id")

但我想知道的是,是否有一种更优雅的方法来检查这一点:例如,在我的基本模型中添加一个约束,禁止在数据库中添加这样一个不一致的记录。

我不知道有任何直接的方法来直接在数据库上实现这种两级检查

事实上,数据库应该知道的唯一一致性是新的
RtspServerEndpoint
实例将属于正确的
Camera
实例。但是默认情况下,通过创建
RtspServerEndpoint
实例的方式,这是正确的

因此,在我看来,对POST请求URL中的
site\u id
正确性的检查应该在代码的逻辑中实现。我可能会这样做:

@handler(..., method='POST')
def rtspserverendpoint(site_id: int, camera_id: int):
    # find camera, which will allow us to check the correctness of the site_id as well
    camera = db.session.query(Camera).get(camera_id)

    if camera is None:
        raise Exception(f"No camera with this {camera_id=}.")

    if camera.site_id != site_id:
        raise Exception(f"Camera with this {camera_id=} does not belong to the site with {site_id=}.")

    new_obj = RtspServerEndpoint(
        ...,
        camera_id=camera_id,
        ...,
    )

    db.session.add(new_obj)
    db.session.commit()

ForeignKey
是约束条件。感谢您的回答。这实际上是我想要做的,除了我会得到相机id和站点id上都有过滤器的相机。然后,如果相机没有,这意味着相机id和站点id之间存在不一致,我不确定你关于“不一致”的说法是否正确。因为当id为
Camera\u id
的摄像头根本不存在时,您也会得到
None
。因此,分别检查这两个条件更可靠。
@handler(..., method='POST')
def rtspserverendpoint(site_id: int, camera_id: int):
    # find camera, which will allow us to check the correctness of the site_id as well
    camera = db.session.query(Camera).get(camera_id)

    if camera is None:
        raise Exception(f"No camera with this {camera_id=}.")

    if camera.site_id != site_id:
        raise Exception(f"Camera with this {camera_id=} does not belong to the site with {site_id=}.")

    new_obj = RtspServerEndpoint(
        ...,
        camera_id=camera_id,
        ...,
    )

    db.session.add(new_obj)
    db.session.commit()