๐Ÿ”ซ Django choices field

๊ธฐ๋ณธ ์‚ฌ์šฉ๋ฒ•

๋‘ ๊ฐœ์˜ ์•„์ดํ…œ์œผ๋กœ ์ด๋ฃจ์–ด์ง„ ํŠœํ”Œ์„ ํ•„๋“œ๋กœ ์‚ฌ์šฉํ•œ๋‹ค.

๊ฐ ํŠœํ”Œ์˜ ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๋Š” DB์— ์ €์žฅํ•  ์‹ค์ œ ๊ฐ’์ด๊ณ , ๋‘ ๋ฒˆ์งธ ์š”์†Œ๋Š” display ์šฉ ์ด๋ฆ„์ด๋‹ค. ์˜ˆ๋ฅผ ๋“ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

YEAR_IN_SCHOOL_CHOICES = [
    ('FR', 'Freshman'),
    ('SO', 'Sophomore'),
    ('JR', 'Junior'),
    ('SR', 'Senior'),
]

์œ„์™€ ๊ฐ™์ด CHOICES ํ•„๋“œ๋ฅผ ๋ฏธ๋ฆฌ ์ •์˜ํ•ด๋‘๊ณ  CharField์— ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ์ผ๋ฐ˜์ ์ด๋‹ค.

from django.db import models


class Student(models.Model):
    FRESHMAN = 'FR'
    SOPHOMORE = 'SO'
    JUNIOR = 'JR'
    SENIOR = 'SR'
    YEAR_IN_SCHOOL_CHOICES = [
        (FRESHMAN, 'Freshman'),
        (SOPHOMORE, 'Sophomore'),
        (JUNIOR, 'Junior'),
        (SENIOR, 'Senior'),
    ]
    year_in_school = models.CharField(
        max_length=2,
        choices=YEAR_IN_SCHOOL_CHOICES,
        default=FRESHMAN,
    )

    def is_upperclass(self):
        return self.year_in_school in (self.JUNIOR, self.SENIOR)

๊ทธ๋ฃนํ™”

๋‹ค์Œ์ฒ˜๋Ÿผ CHOICES๋ฅผ ๊ทธ๋ฃน์œผ๋กœ ์ •์˜ํ•  ์ˆ˜๋„ ์žˆ๋‹ค.

MEDIA_CHOICES = [
    ('Audio', (
            ('vinyl', 'Vinyl'),
            ('cd', 'CD'),
        )
    ),
    ('Video', (
            ('vhs', 'VHS Tape'),
            ('dvd', 'DVD'),
        )
    ),
    ('unknown', 'Unknown'),
]

๊ฐ ํŠœํ”Œ์˜ ์ฒซ ๋ฒˆ์งธ ์š”์†Œ๋Š” ๊ทธ๋ฃน์— ์ ์šฉ ํ•  ์ด๋ฆ„์ด๋‹ค. ๋‘ ๋ฒˆ์งธ ์š”์†Œ๋Š” 2 ๊ฐœ์˜ ํŠœํ”Œ์„ ๋ฐ˜๋ณต ํ•  ์ˆ˜ ์žˆ์œผ๋ฉฐ ๊ฐ 2 ๊ฐœ์˜ ํŠœํ”Œ์—๋Š” ์‹ค์ œ ๊ฐ’๊ณผ display ์ด๋ฆ„์ด ๋“ค์–ด ์žˆ๋‹ค. ๊ทธ๋ฃนํ™” ๋œ ์˜ต์…˜์€ ๋‹จ์ผ ๋ชฉ๋ก ๋‚ด์—์„œ ๊ทธ๋ฃนํ™”๋˜์ง€ ์•Š์€ ์˜ต์…˜(unknown)๊ณผ ๊ฒฐํ•ฉ ๋  ์ˆ˜ ์žˆ๋‹ค.

getFOOdisplay()

choices๊ฐ€ ์„ค์ •๋œ ๋ชจ๋“  ํ•„๋“œ๋Š” get_FOO_display() ๋ฉ”์„œ๋“œ๋ฅผ ๊ฐ–๋Š”๋‹ค. ์ด ๋ฉ”์„œ๋“œ๋Š” ์‚ฌ๋žŒ์ด ์ฝ์„ ์ˆ˜ ์žˆ๋Š” display ์šฉ ๊ฐ’์„ ๋ฐ˜ํ™˜ํ•œ๋‹ค.

์˜ˆ๋ฅผ ๋“ค๋ฉด ๋‹ค์Œ๊ณผ ๊ฐ™๋‹ค.

from django.db import models


class Person(models.Model):
    SHIRT_SIZES = (
        ('S', 'Small'),
        ('M', 'Medium'),
        ('L', 'Large'),
    )
    name = models.CharField(max_length=60)
    shirt_size = models.CharField(max_length=2, choices=SHIRT_SIZES)
>>> p = Person(name="Fred Flintstone", shirt_size="L")
>>> p.save()
>>> p.shirt_size
'L'
>>> p.get_shirt_size_display()
'Large'

view ๋ฟ๋งŒ ์•„๋‹ˆ๋ผ template์—์„œ๋„ ๋งˆ์ฐฌ๊ฐ€์ง€๋กœ ์ž˜ ๋™์ž‘ํ•œ๋‹ค.

References


Written by@ugaemi
Record things I want to remember

๐Ÿฑ GitHub๐Ÿ“š Reading Space