Last Updated: February 25, 2016
·
1.27K
· lukas

Django Number Choices

I know the title may be misleading, but there are some situations where you want the choices of a Model of ChoiceField to be a specific range of numbers.

Since Django expects an iterable consisting itself of iterables of exactly two items (e.g. [[1, 1] , [2, 2]]), we can't simply supply a range.

First things first, here's the solution (well, one of the many):

choices=zip(*[range(start, end + 1)] * 2)

Let me explain: first, there's the range that we want to convert from [1, 2, ... n] to [[1, 1], [2, 2], ... [n, n]]. We then 'duplicate' the list (well, create a reference) by multiplying it with 2, effectively becoming [[1, 2, ... n], [1, 2, ... n]].

Since the zip function doesn't take a list but each list as a single argument, we unpack our list with the * and we're done.