Ben
Ben

Reputation: 16610

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

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.

Upvotes: 33

Views: 27168

Answers (2)

Pablo Ruiz Ruiz
Pablo Ruiz Ruiz

Reputation: 636

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

Upvotes: 7

Torsten Engelbrecht
Torsten Engelbrecht

Reputation: 13486

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)]

Upvotes: 48

Related Questions