I have the Dropdown Single Select Box "Month" with 3 options "January", "February" and "March" as shown below:
This is the code for the Dropdown Single Select Box "Month" in "Date" class below:
# "store/models.py"
from django.db import models
class Date(models.Model):
class Months(models.TextChoices):
JANUARY = 'JAN', 'January'
FEBRUARY = 'FEB', 'February'
MARCH = 'MAR', 'March'
month = models.CharField(max_length=100, choices=Months.choices)
And, this is the old version code for the Dropdown Single Select Box "Month" in "Date" class below which is equivalent to the above code:
# "store/models.py"
from django.db import models
class Date(models.Model):
JANUARY = 'JAN'
FEBRUARY = 'FEB'
MARCH = 'MAR'
MANTHS = [
(JANUARY, 'January'),
(FEBRUARY, 'February'),
(MARCH, 'March')
]
month = models.CharField(max_length=100, choices=MANTHS)
Now, if I choose "February" and click on "SAVE", what is stored in database? "FEBRUARY"? "FEB"? or "February"?
"FEB" is stored in database. Actually as shown below, "FEBRUARY" is just a variable and "FEB" is the value stored in DB(Database) and "February" is the option displayed in the Dropdown Single Select Box "Month" on "Add date" page of Django Admin(GUI):
# "store/models.py"
from django.db import models
class Date(models.Model):
class Months(models.TextChoices):
# |Variable| | DB | | Option |
JANUARY = 'JAN', 'January'
FEBRUARY = 'FEB', 'February'
MARCH = 'MAR', 'March'
month = models.CharField(max_length=100, choices=Months.choices)
For the old version code below:
# "store/models.py"
from django.db import models
class Date(models.Model):
# |Variable| | DB |
JANUARY = 'JAN'
FEBRUARY = 'FEB'
MARCH = 'MAR'
MANTHS = [
# |Variable| | Option |
(JANUARY, 'January'),
(FEBRUARY, 'February'),
(MARCH, 'March')
]
month = models.CharField(max_length=100, choices=MANTHS)
And as shown below, "FEB" is stored in database(SQLite)
In addition, by adding this code below to "Date" class:
def __str__(self):
return self.month
You can check what is stored in database on "Select date to change" page of Django Admin(GUI) as shown below:
This is the full code below:
# "store/models.py"
from django.db import models
class Date(models.Model):
class Months(models.TextChoices):
# |Variable| | DB | | Option |
JANUARY = 'JAN', 'January'
FEBRUARY = 'FEB', 'February'
MARCH = 'MAR', 'March'
month = models.CharField(max_length=100, choices=Months.choices)
def __str__(self):
return self.month
And, this is the full code for the old version below:
# "store/models.py"
from django.db import models
class Date(models.Model):
# |Variable| | DB |
JANUARY = 'JAN'
FEBRUARY = 'FEB'
MARCH = 'MAR'
MANTHS = [
# |Variable| | Option |
(JANUARY, 'January'),
(FEBRUARY, 'February'),
(MARCH, 'March')
]
month = models.CharField(max_length=100, choices=MANTHS)
def __str__(self):
return self.month