I am new to Python and Flask and I am trying to loop through this dictionary below as a test pre-getting data from a DB and sort it out on a specific field/column other than just printing the list out in the order I have created it.
i.e. This will simply print out the
{% for data in db_get_show_application_overview %}
<TD> {{ data.sao_application }} </TD>
<TD> {{ data.sao_primary_app_name }} </TD>
<TD> {{ data.sao_physical_server_name }} </TD>
{% endfor %}
But I would like to be able to order this say via the sao_physical_server_name field or the sao_primary_app_name as an example and not via the order it is created in as it would have been in a dB for example. I have looked to find something similar but I cannot seem to find anything. If this has been already answered then sorry.
Is this possible?
db_get_show_application_overview = [
{
'sao_application': {'name': 'appname1'},
'sao_line_num': '1',
'sao_primary_app_name': 'A Application',
'sao_physical_server_name': 'server1'
},
{
'sao_application': {'name': 'appname2'},
'sao_line_num': '2',
'sao_primary_app_name': 'C Application',
'sao_physical_server_name': 'server1'
},
{
'sao_application': {'name': 'appname3'},
'sao_line_num': '3',
'sao_primary_app_name': 'B Application',
'sao_physical_server_name': 'server1'
}
]
Thank you,
Paul
CodePudding user response:
Try to sort the list in backend before passing it to the template.
Instead of passing it as it is:
return render_tamplate('your_template.html', db_get_show_application_overview=db_get_show_application_overview)
pass the sorted one:
return render_tamplate('your_template.html', db_get_show_application_overview=sorted(db_get_show_application_overview, key=your_key_function))
You can sort the list using key function. This is the sorted documentation and this is good tutorial for how to use the key function.
For example you can sort them based on sao_line_num
:
sorted(db_get_show_application_overview, key=lambda item: item['sao_line_num'])
CodePudding user response:
Does this help:-
db_get_show_application_overview = [
{
'sao_application': {'name': 'appname1'},
'sao_line_num': '1',
'sao_primary_app_name': 'A Application',
'sao_physical_server_name': 'server1'
},
{
'sao_application': {'name': 'appname2'},
'sao_line_num': '2',
'sao_primary_app_name': 'C Application',
'sao_physical_server_name': 'server1'
},
{
'sao_application': {'name': 'appname3'},
'sao_line_num': '3',
'sao_primary_app_name': 'B Application',
'sao_physical_server_name': 'server0'
}]
print(sorted(db_get_show_application_overview, key = lambda x: x['sao_physical_server_name']))