So. The following isn't very 'smart' ;)
MONTHS = (
('Jan', 'Jan'),
('Feb', 'Feb'),
('Mar', 'Mar'),
('Apr', 'Apr'),
('May', 'May'),
('Jun', 'Jun'),
('Jul', 'Jul'),
('Aug', 'Aug'),
('Sep', 'Sep'),
('Oct', 'Oct'),
('Nov', 'Nov'),
('Dec', 'Dec'),
)
YEARS = (
('1995', '1995'),
('1996', '1996'),
('1997', '1997'),
('1998', '1998'),
('1999', '1999'),
('2000', '2000'),
('2001', '2001'),
('2002', '2002'),
('2003', '2003'),
('2004', '2004'),
('2005', '2005'),
('2006', '2006'),
('2007', '2007'),
('2008', '2008'),
('2009', '2009'),
('2010', '2010'),
)
I'm newer to python, and would love to produce stuff like this 'pythonically'.
Such as,
Thanks Stackers'
Django Field Choices. According to documentation Field Choices are a sequence consisting itself of iterables of exactly two items (e.g. [(A, B), (A, B) …]) to use as choices for some field. For example, consider a field semester which can have options as { 1, 2, 3, 4, 5, 6 } only.
Create a single record with save() or create() To create a single record on a Django model, you just need to make an instance of a model and invoke the save() method on it. Listing 8-1 illustrates the process to create a single record for a model called Store .
If you are using Google App Engine or MongoDB as your backend, and you are using the djangoappengine library, there is a built in ListField that does exactly what you want. Further, it's easy to query the Listfield to find all objects that contain an element in the list.
The simplest, easiest, best and new way is using "models. TextChoices" which is built-in which means "You don't need to install any packages".
In [17]: from datetime import datetime
In [18]: tuple((str(n), str(n)) for n in range(1995, datetime.now().year + 1))
Out[18]:
(('1995', '1995'),
('1996', '1996'),
('1997', '1997'),
('1998', '1998'),
('1999', '1999'),
('2000', '2000'),
('2001', '2001'),
('2002', '2002'),
('2003', '2003'),
('2004', '2004'),
('2005', '2005'),
('2006', '2006'),
('2007', '2007'),
('2008', '2008'),
('2009', '2009'),
('2010', '2010'))
In [19]: import calendar
In [20]: tuple((m, m) for m in calendar.month_abbr[1:])
Out[20]:
(('Jan', 'Jan'),
('Feb', 'Feb'),
('Mar', 'Mar'),
('Apr', 'Apr'),
('May', 'May'),
('Jun', 'Jun'),
('Jul', 'Jul'),
('Aug', 'Aug'),
('Sep', 'Sep'),
('Oct', 'Oct'),
('Nov', 'Nov'),
('Dec', 'Dec'))
Try using zip()
to make a list of two-tuples.
MONTHS = ('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec')
somemonth = models.TextField(max_length=3, choices=zip(MONTHS,MONTHS))
choices
will be set to [('Jan', 'Jan'), ('Feb', 'Feb'), ...]
.
In response to the comments on this answer, the "tuple" list comprehension version would be:
tuple((m, m) for m in MONTHS)
Versus the zip version:
tuple(zip(MONTHS, MONTHS))
But strictly speaking, Django doesn't need a tuple of choices, so:
zip(MONTHS, MONTHS)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With