S
S
sazhyk2016-05-16 13:33:27
Django
sazhyk, 2016-05-16 13:33:27

How to create an iterator of two element tuples?

There is an argument in the Django models, in the field settings , which will be displayed on the page choicesin the form . accepts<select>choices

An iterator (such as a list or tuple) of 2-tuples specifying the value options for the field.
An example from the Django documentation:
YEAR_IN_SCHOOL_CHOICES = (
    ('FR', 'Freshman'),
    ('SO', 'Sophomore'),
    ('JR', 'Junior'),
    ('SR', 'Senior'),
    ('GR', 'Graduate'),
)

The question is actually the following, how to create this iterator in a function, if it is necessary to return such an iterator:
YEARS_BIRTHS = (
    ('1950', '1950'),
    ('1951', '1951'),
    ('1952', '1952'),
    ...
)
I understand that these are elementary things in python, but I can’t figure out how.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
abcd0x00, 2016-05-16
@sazhyk

>>> def gen(start, end):
...     return ((str(i), str(i)) for i in range(start, end + 1))
... 
>>> tuple(gen(1950, 1952))
(('1950', '1950'), ('1951', '1951'), ('1952', '1952'))
>>>

A
Artem, 2016-05-16
@ulkoart

def year_func(*args):
  res = ()
  for year in range(args[0], args[1]):
    res += ((str(year), str(year)),)
  return res

class ModelName(models.Model):
    year = models.CharField(max_length=50, choices=year_func(1990, 2000), verbose_name='год')

CharField - change to what you need.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question