How to only execute a query when a relevant selection is made by the user

40 Views Asked by At

I have a streamlit app that allows the user to make selections via a st.selectbox(). Eg:

selection = st.selectbox("make a selection",["a","b","c"])

Each selection triggers a query to my database, a process that is fairly expensive.

Right now, with pseducode:

ddict = {"a":query_a(), "b":query_b(), "c":query_c()}
df = ddict[selection]

When my app loads, it runs all 3 queries (and caches them). I would like the behaviour where the query is only triggered if the user selects the relevant choice in the selectbox. How should this be done?

1

There are 1 best solutions below

0
On BEST ANSWER

Function will only execute if selection differs from the first one, as the results will be cached and result will be returned instead of executing it again

@st.cache
def query_results(selection):
    # execute query based on selection
    return df

if selection:
    df = query_results(selection)

Remove the query execution from your pseudocode, as it will be automatically executed when the function is called.