Reputation: 1347
could you tell me if the following code is correct? I want to create a drop down that in the django admin will show a dropdown with a selection of integer:
class Test(TimeStampedModel):
"""
Test specifications
"""
TIME_INTERVALS = Choices(
('SECONDS_30', 30)
('SECONDS_60', 60)
('SECONDS_90', 90)
('SECONDS_120', 120)
('SECONDS_150', 150)
('SECONDS_300', 300)
)
sample_time = models.PositiveSmallIntegerField(choices=TIME_INTERVALS, default=TIME_INTERVALS.SECONDS_30)
Thank you
Upvotes: 0
Views: 185
Reputation: 3527
The pattern is:
# list of tuples:
INTEGER_CHOICES = (
(<int>, <string>),
...
)
Where <int>
is the value stored in the DB and <string>
is what is displayed to users in the drop down menu
A typical use case is as follows:
models.py
SECONDS_30 = 30
SECONDS_90 = 90
...
TIME_INTERVALS = (
(SECONDS_30, "30 Seconds"),
(SECONDS_90, "90 Seconds"),
...
)
class Test(...):
sample_time = models.PositiveSmallIntegerField(choices=TIME_INTERVALS, ...)
...
Then in your views:
views.py
from . import models
# update sample time:
test_instance = models.Test.objects.get(...)
test_instance.sample_time = models.SECONDS_30
test_instance.save()
...
Upvotes: 1