dataviz: using natural order for alphabetical data sort (#62317)

This commit is contained in:
Corentin Sechet 2022-03-08 17:11:00 +01:00
parent 411c0f025e
commit 5f918b53c0
2 changed files with 33 additions and 1 deletions

View File

@ -16,6 +16,7 @@
import copy
import os
import re
from collections import OrderedDict
from datetime import date, datetime, timedelta
@ -599,8 +600,15 @@ class ChartNgCell(CellBase):
return new_data
def sort_values(self, chart, data):
if self.sort_order == 'alpha':
tmp_items = sorted(zip(chart.x_labels, data), key=lambda x: x[0])
digit_re = re.compile('([0-9]+)')
def natural_sort_key(item):
return [int(text) if text.isdigit() else text.lower() for text in digit_re.split(item[0])]
tmp_items = sorted(zip(chart.x_labels, data), key=natural_sort_key)
elif self.sort_order == 'asc':
tmp_items = sorted(zip(chart.x_labels, data), key=lambda x: (x[1] or 0))
elif self.sort_order == 'desc':

View File

@ -142,6 +142,12 @@ VISUALIZATION_JSON = [
'name': 'fifteenth visualization (only loop labels)',
'slug': 'fifteenth',
},
{
'data-url': 'https://bijoe.example.com/visualization/16/json/',
'path': 'https://bijoe.example.com/visualization/16/iframe/?signature=123',
'name': 'sixteenth visualization (numerical labels)',
'slug': 'sixteenth',
},
]
@ -306,6 +312,17 @@ def bijoe_mock(url, request):
'measure': 'integer',
}
return {'content': json.dumps(response), 'request': request, 'status_code': 200}
if url.path == '/visualization/16/json/':
response = {
'format': '1',
'data': [1, 2, 3, 4, 5, 6, 7, 8, 9],
'axis': {
'x_labels': ['item2', 'foo', 'item20', 'item10', 'foo2', 'Item3', '10', '4', 'item1'],
'y_labels': [],
},
'measure': 'integer',
}
return {'content': json.dumps(response), 'request': request, 'status_code': 200}
STATISTICS_LIST = {
@ -964,6 +981,13 @@ def test_chartng_cell_sort_order_alpha(app, statistics):
assert chart.x_labels == ['a', 'b', 'c']
assert chart.raw_series == [([], {'title': ''})]
cell.statistic = Statistic.objects.get(slug='sixteenth')
cell.sort_order = 'alpha'
cell.save()
chart = cell.get_chart()
assert chart.x_labels == ['4', '10', 'foo', 'foo2', 'item1', 'item2', 'Item3', 'item10', 'item20']
assert chart.raw_series == [([8, 7, 2, 5, 9, 1, 6, 4, 3], {'title': ''})]
@with_httmock(bijoe_mock)
def test_chartng_cell_sort_order_desc(app, statistics):