Home > OS >  Using kwargs with filter_by (Sqlalchemy)
Using kwargs with filter_by (Sqlalchemy)

Time:09-28

So I'm currently trying to create a dynamic function, that will take 1 kwarg, and use that in it's filter_by.

This is what the function currently looks like:

    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. But currently it seems that the 'entry' paramter in both of the filter_by functions, are interpreted literally, and not as variables? 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"])

CodePudding user response:

You can use **data in filter_by directly to get the correct result.

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

** unpacks your data into key-value pairs and passes them to the filter_by function.

Also, you probably dont want to query twice just to check your if statement.

  • Related