[Django]-Some Django ChoiceFields with the same choice source

3👍

Use a list for DAYS:

class MyModel(models.Model):
    DAYS = [str(d), str(d)) for d in range(1, 29)]
    day1 = models.CharField('Day 1', max_length=3, null=True, blank=True, choices=DAYS)
    day2 = models.CharField('Day 2', max_length=3, null=True, blank=True, choices=DAYS)

Currently, DAYS is a generator. When you access it the first time to get choices for day1, it returns the results you expect. However, the generator has then been consumed, so you get an empty list when you try to get the choices for day2.

You can see this by trying the following in the Python shell:

>>> DAYS = ((str(d), str(d)) for d in range(1,5))
>>> print(list(DAYS))
[('1', '1'), ('2', '2'), ('3', '3'), ('4', '4')]
>>> print(list(DAYS))
[]
>>>

Leave a comment