From f5b80771d21882caf4d8031b544450983559011c Mon Sep 17 00:00:00 2001 From: Martin Hauser Date: Thu, 2 Oct 2025 23:14:55 +0200 Subject: [PATCH] fix(utilities): Enhance ranges_to_string for improved clarity Updates the `ranges_to_string` function to handle single-value ranges and improve string representation. Refines the formatting logic to include isolated values when the lower and upper bounds of a range are identical. Fixes #20475 --- netbox/utilities/data.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/netbox/utilities/data.py b/netbox/utilities/data.py index 7b50d26b84d..4dbbf38cf96 100644 --- a/netbox/utilities/data.py +++ b/netbox/utilities/data.py @@ -137,8 +137,17 @@ def check_ranges_overlap(ranges): def ranges_to_string(ranges): """ - Generate a human-friendly string from a set of ranges. Intended for use with ArrayField. For example: - [[1, 100)], [200, 300)] => "1-99,200-299" + Converts a list of ranges into a string representation. + + This function takes a list of range objects and produces a string + representation of those ranges. Each range is represented as a + hyphen-separated pair of lower and upper bounds, with inclusive or + exclusive bounds adjusted accordingly. If the lower and upper bounds + of a range are the same, only the single value is added to the string. + Intended for use with ArrayField. + + Example: + [NumericRange(1, 5), NumericRange(8, 9), NumericRange(10, 12)] => "1-5,8,10-12" """ if not ranges: return '' @@ -146,7 +155,7 @@ def ranges_to_string(ranges): for r in ranges: lower = r.lower if r.lower_inc else r.lower + 1 upper = r.upper if r.upper_inc else r.upper - 1 - output.append(f'{lower}-{upper}') + output.append(f"{lower}-{upper}" if lower != upper else str(lower)) return ','.join(output)