DevOps/Django

[Django] 장고 모델(ORM)

bestwish 2022. 5. 11. 00:23

장고의 모델을 만들어 준 후, 쿼리가 어떻게 작동했는지 확인 할 수 있다.

 

모델 작동 확인

1. 모델 생성

# <app>/models.py
class Post(models.Model):
    message = models.TextField()
    created_at = models.DateTimeField(auto_now_add=True) 
    updated_at = models.DateTimeField(auto_now=True) 
  • auto_now_add : 최초 생성 시간을 1번 사용하여 저장, 갱신 불가능
  • auto_now : 장고 모델이 저장 될 때마다 현재날짜(시간)으로 갱신, 갱신 가능

 

2. makemigration, migrate

shell

python manage.py makemigrations <app명>
python manage.py migrate <app명>

 

3. 모델 쿼리 확인

shell

python manage.py sqlmigrate <app명>  0001_initial

 

4. 결과

BEGIN;
--
-- Create model Post
--
CREATE TABLE "instagram_post" ("id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "message" text NOT NULL, "created_at" datetime NOT NULL, "updated_at" datetime NOT NULL);
COMMIT;

 

모델필드 타입

타입 타입명
Primary Key AutoField, BigAutoField
문자열 CharField, TextField, SlugField
날짜/시간 DateField, TimeField, DateTimeField, DurationField
참/거짓 BooleanField, NullBooleanField
숫자 IntegerField, SmallIntegerField, PositiveIntegerField, PositiveSmallIntegerField, BigIntegerField,DecimalField, FloatField
파일 BinaryField, FileField, ImageField, FilePathField
이메일 EmailField
URL URLField
UUID UUIDFiled
아이피 GenericIPAddressField
Relationship Types ForeignKey, ManyToManyField, OneToOneField

 

자주쓰는 필드 공통 옵션

옵션 설명
blank 장고 단에서 validation시에 empty 허용 여부 (디폴트 : False )
null (DB옵션) null 허용 여부 (디폴트 : False)
db_index (DB옵션) 인덱스 필드 여부 (디폴트 : False)
default 디폴트 값 지정, 혹은 값을 리턴해줄 함수 지정
unique (DB옵션) 현재 테이블 내에서 유일성 여부 (디폴트 : False)
choices select 박스 소스로 사용
validators validators를 수행할 함수를 다수 지정
verbose_name 필드 레이블, 미지정시 필드명이 사용
help_text 필드 입력 도움말