Info-Tech

DJango 5.0 주요 변화 본문

서버이야기

DJango 5.0 주요 변화

개발 로그를 쌓고 싶은 블로거 2023. 12. 5. 16:45


db_default  필드가 추가됨

Example
# db_default 값은 데이터베이스에서 계산된 기본값으로 터럴 값이나 Now와 같은 데이터베이스 함수일 수 있다.
class MyModel(models.Model):
    age = models.IntegerField(db_default=18)
    created = models.DateTimeField(db_default=Now())
    circumference = models.FloatField(db_default=2 * Pi())

 

GeneratedField  필드가 추가됨

class MyModel(models.Model):
    age = models.IntegerField(db_default=18)
    created = models.DateTimeField(db_default=Now())
    circumference = models.FloatField(db_default=2 * Pi())

GeneratedField  필드가 추가됨
Example
class Square(models.Model):
    side = models.IntegerField()
    area = models.GeneratedField(
        expression=F("side") * F("side"),
        output_field=models.BigIntegerField(),
        db_persist=True,
    )


area의 경우 side * side인데, 해당값을 하나의 데이터가 생성시 자동적으로 area을 계산해서 넣어주는 방식.

choices 필드의 유연성 증가

1. Field.choices (모델 필드용) 및 ChoiceField.choices (폼 필드용)는 값을 선언할 때 더 많은 유연성을 제공합니다.

Exameple
from django.db import models

Medal = models.TextChoices("Medal", "GOLD SILVER BRONZE")

SPORT_CHOICES = [
    ("Martial Arts", [("judo", "Judo"), ("karate", "Karate")]),
    ("Racket", [("badminton", "Badminton"), ("tennis", "Tennis")]),
    ("unknown", "Unknown"),
]


class Winner(models.Model):
    name = models.CharField(...)
    medal = models.CharField(..., choices=Medal.choices)
    sport = models.CharField(..., choices=SPORT_CHOICES)

  
보시면, SPORT_CHOICES에서 tuple 형식 이외에도 List[Tuple] 형식등 다양하게 제공

2. 호출 가능한 객체를 받아들이는 기능을 추가했으며, 또한 열거형 타입을 확장하기 위해 .choices를 직접 사용할 필요가 없어졌습니다

Example
from django.db import models

Medal = models.TextChoices("Medal", "GOLD SILVER BRONZE")

SPORT_CHOICES = {  # Using a mapping instead of a list of 2-tuples.
    "Martial Arts": {"judo": "Judo", "karate": "Karate"},
    "Racket": {"badminton": "Badminton", "tennis": "Tennis"},
    "unknown": "Unknown",
}


def get_scores():
    return [(i, str(i)) for i in range(10)]


class Winner(models.Model):
    name = models.CharField(...)
    medal = models.CharField(..., choices=Medal)  # Using `.choices` not required.
    sport = models.CharField(..., choices=SPORT_CHOICES)
    score = models.IntegerField(choices=get_scores)  # A callable is allowed.


https://docs.djangoproject.com/en/5.0/releases/5.0/

Comments