Shouldn't this be `query = query.filter(filter)`?