在添加 Flask、SQLAlchemy 之前检查 table 行中的值是否已经存在

Checking if values in row in table already exists before adding in Flask, SQLAlchemy

我有一个 UserService 连接 table 看起来是这样的:

[
    {
        "id": 1,
        "service_id": 1,
        "user_id": 1
    },
    {
        "id": 2,
        "service_id": 2,
        "user_id": 1
    },
    {
        "id": 3,
        "service_id": 2,
        "user_id": 2
    },
    {
        "id": 4,
        "service_id": 3,
        "user_id": 1
    },
    {
        "id": 5,
        "service_id": 3,
        "user_id": 2
    }
]

创建新的 UserService 时,如果值已经存在,我不希望用户能够添加条目。我当前的 if 语句当前正在返回 else 语句。我在这里做错了什么?

@bp.route('/user/<userid>/add-service/<serviceid>', methods=['POST'])
def add_service_to_user(userid, serviceid):

    user = db_session.query(User).filter(User.id == userid).first()
    service = db_session.query(Service).filter(Service.id == serviceid).first()

    all_user_services = db_session.query(UserService).all()

    for service in all_user_services:
        if serviceid == service.service_id and userid == service.user_id:
            return jsonify({'Message': f'User with id: {userid} already has Service with id: {serviceid}'})
    else:
        return 'hello'

您可以在数据库端执行此操作,只需在 .filter()[=15= 中使用 and 运算符]

.query(Service).filter(Service.id == serviceid && Service.user_id == userid).first()

您可能还想为 serviceiduserid 参数定义类型,因为它们是整数。 代码可能看起来像

@bp.route('/user/<int:userid>/add-service/<int:serviceid>', methods=['POST'])
def add_service_to_user(userid, serviceid):

    service = db_session.query(Service).filter(Service.id == serviceid && Service.user_id == userid).first()

    if service is not None:
        return jsonify({'Message': f'User with id: {userid} already has Service with id: {serviceid}'})
    else:
        return 'hello'