简体   繁体   English

将 kwargs 与 filter_by 一起使用(Sqlalchemy)

[英]Using kwargs with filter_by (Sqlalchemy)

So I'm currently trying to create a dynamic function, that will take 1 kwarg, and use that in it's filter_by.所以我目前正在尝试创建一个动态 function,这将需要 1 kwarg,并在它的 filter_by 中使用它。

This is what the function currently looks like:这是 function 目前的样子:

    def Get_from_var(session, **data):
    for entry in data:
        if bool(session.query(Tutor).filter_by(entry=data[entry]).first()):
            return session.query(Tutor).filter_by(entry=data[entry]).first()
        return "No tutor found"

I know that my function will only recieve 1 kwarg, so I'm not worried about some weird exceptions.我知道我的 function 只会收到 1 kwarg,所以我不担心一些奇怪的异常。 But currently it seems that the 'entry' paramter in both of the filter_by functions, are interpreted literally, and not as variables?但目前看来,两个 filter_by 函数中的 'entry' 参数都是按字面解释的,而不是变量? Because It tells me that "tutor has no property 'entry'"因为它告诉我“导师没有财产‘入口’”

This is how I'm currently calling it:这就是我目前的称呼:

tutor = Tutor.Get_from_var(session, tutor_id=filters["id"])

You can use **data in filter_by directly to get the correct result.您可以直接使用filter_by中的**data来获得正确的结果。

session.query(Tutor).filter_by(**data).first()

** unpacks your data into key-value pairs and passes them to the filter_by function. ** 将您的数据解包为键值对并将它们传递给 filter_by function。

Also, you probably dont want to query twice just to check your if statement.此外,您可能不想查询两次只是为了检查您的 if 语句。

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

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