Django IntegerField with Choice Options (how to create 0-10 integer options)

Question:

I want to limit the field to values 0-10 in a select widget.

field=models.IntegerField(max_length=10, choices=CHOICES)

I could just write out all the choices tuples from (0,0),(1,1) on, but there must be an obvious way to handle this.

Help is highly appreciated.

Asked By: Ben

||

Answers:

Use a Python list comprehension:

CHOICES = [(i,i) for i in range(11)]

This will result in:

[(0, 0), (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10,10)]
Answered By: Torsten Engelbrecht

As well as @Torsten has mentioned, you could improve it by:

field = models.IntegerField(choices=list(zip(range(1, 10), range(1, 10))), unique=True)

But remember this will gives you from 1 to 9. Put range (1,11) if you want until 10

Answered By: Pablo Ruiz Ruiz
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.