Search code examples
pythonif-statementcallbackplotly-dash

How to have initial data table if I initialize the filter in dash ? (callback problem)


I want to have an initial data table when I reset the filter.

This is the initial status.

enter image description here

And if I applied filter, it would give me like this :

enter image description here

But after that, if I remove (or reset) the filter, it gives me nothing :

enter image description here

Here is my code. I think it is not very useful to give the entire code because it is a little long.

@app.callback(
    Output('update-rowdata-grid', 'rowData'),
    Input({'type': 'filter_cat',"table":ALL ,'index': ALL}, 'value'),
    # Input({'type': 'filter_num', 'index': MATCH}, 'value'),
    # Input({'type': 'filter_date', 'index': MATCH}, 'value')
    State('filter_table', 'value'),
    State('second_filter','value'),
    
)
def apply_filter(cat,selected_table,selected_columns):
    df = get_selected_dataframe(selected_table)
    dff = df.copy()
    column_type = df[selected_columns].dtype
    if column_type == 'object' and cat:
        dff = dff[dff[selected_columns].isin(cat[0])]
    else:
        return df.to_dict('records')
        

    return dff.to_dict('records')

I think we can use some of the If-elif tricks, but I don't have any idea where to start.

Can you help me ?


Solution

  • Given the context of the following question, I suspect the same problem: extra condition based on the second_filter. Once removed, it makes it work at least on categories.

    @app.callback(
        Output('update-rowdata-grid', 'rowData', allow_duplicate=True),
        Input({'type': 'filter_cat', "table": ALL, 'index': ALL}, 'value'),
        State({'type': 'filter_cat', "table": ALL, 'index': ALL}, 'id'),
        State('filter_table', 'value'),
        prevent_initial_call=True)
    def apply_filter(cat, filter_ids, selected_table):
    
        dff = get_selected_dataframe(selected_table).copy()
    
        for filter_id, filter_value in zip(filter_ids, cat):
            if filter_value:
                dff = dff[dff[filter_id['index']].isin(filter_value)]
    
        return dff.to_dict('records')