开发者

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, choi开发者_如何学编程ces=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.


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


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜