python / expert
Snippet
Custom URL Path Converter for Comma-Separated Integer Arrays
Django's path converter architecture enables explicit URL parameter parsing into Python data types before view execution. By defining regex patterns and bi-directional transformation methods (to_python and to_url), comma-separated query parameters are safely decoded into integer lists directly in the routing layer.
snippet.py
python
1
2
3
4
5
6
7
8
9
10
11
12
from django.urls import register_converterclass IntArrayConverter:regex = r'\d+(,\d+)*'def to_python(self, value: str) -> list[int]:return [int(item) for item in value.split(',')]def to_url(self, value: list[int]) -> str:return ','.join(map(str, value))register_converter(IntArrayConverter, 'int_array')
django
Breakdown
1
from django.urls import register_converter
Imports Django URL routing function used for registering custom path converters.
2
class IntArrayConverter:
Declares class satisfying Django path converter interface specifications.
3
regex = r'\d+(,\d+)*'
Defines regular expression matching comma-delimited numeric strings.
4
def to_python(self, value: str) -> list[int]:
Converts incoming matched URL parameter string into list of native integers.
5
return [int(item) for item in value.split(',')]
Splits substring by commas and parses each item via list comprehension.
6
def to_url(self, value: list[int]) -> str:
Serializes list of integers back into formatted comma-delimited string for reverse URL lookup.
7
return ','.join(map(str, value))
Maps list elements to strings and joins them with comma delimiters.
8
register_converter(IntArrayConverter, 'int_array')
Registers converter under key alias for immediate path parameter parsing in url patterns.