파이썬(/appserver/apps/calendar/models.py)
from datetime import timezone, datetime
from typing import TYPE_CHECKING
from pydantic import AwareDatetime
from sqlalchemy_utc import UtcDateTime
from sqlmodel import SQLModel, Field, Relationship, Text, JSON, func # ②
from sqlalchemy.dialects.postgresql import JSONB # ①
if TYPE_CHECKING:
from appserver.apps.account.models import User
class Calendar(SQLModel, table=True):
# 생략
topics: list[str] = Field(
sa_type=JSON().with_variant(JSONB(astext_type=Text()), "postgresql"),
description="게스트와 나눌 주제들"
)
JSONB(①)의 astext_type=Text() 인자는 JSONB 열의 값을 텍스트로 변환할 때 사용할 자료형을 Text로 지정한 것입니다(②). 이 인자를 사용하면 SQLAlchemy가 값을 다룰 때 자료형 안정성을 확보하고, 질의 최적화를 하는 데 도움이 됩니다.
이 책에서는 특별한 경우가 아니면 이와 같이 JSON 모델 필드를 정의합니다.