django models-모델 필드타입

BackEnd_Ash.log·2020년 3월 23일
0

참고자료

https://docs.djangoproject.com/en/3.0/ref/models/fields/#field-types

Primary Key

AutoField

Primary Key 는 AutoField 를 option 으로 추가하지 않더라도 , Django 에서 자동으로 지정을 해준다.

BigAutoField

문자열

  • CharField
    max_length 설정이 가능하다 .
  • TextField

SlugField

    slug = models.SlugField(allow_unicode = True , max_length = 100 , unique = True , db_index = True)

www.example.com/article/1
로 하게되면 urls 에 int 값으로 엔드포인트 를 받게된다.
하지만 만약에 이부분이 string 이며 , 띄어쓰기가 있게된다면 ?
www.example.com/article/The%2046%20Year%20Old%20Virgin

이런식으로 입력이 되어진다.
하지만 만약에 slug 를 models 에 필드 넣게된다면

공백은 " - " 로 바뀌게 된다.

image

ImageField

    image      = models.ImageField(blank = True , upload_to='categories/%Y/%m/%d')

upload_to 옵션을 주게 되면 저기 경로에 image 가 저장이 된다.

날짜/시간

DateField

created_db = models.DateTimeField(auto_now_add = True)
# 처음에 추가될때 생성된다.
updated_db = models.DateTimeField(auto_now = True)
# 처음 추가 될때 생성이 되면서 데이터가 바뀔때 마다 같이 바뀌게된다.
  • TimeField
  • DurationField

ForeignKey - 외래키

class Category(models.Model):
	...

class Product(models.Model):
    category   = models.ForeignKey('Category' , on_delete=models.CASCADE)

on_delete

  • on_delete=models.CASCADE
    카테고리도 지워지면 외래키도 지우겠다

  • on_delete=models.PROTECT
    카테고리에 제품이 하나라도 남아있으면 지울수 없게 된다.

주로 역참조를 한다거나 many_to_many 를 사용하게 될때 option 에 추가한다.

related_name 을 설정해 두면 , related_name 으로 설정된 이름으로 찾을 수가 있다.
만약에 그럼 설정하지 않았을경우는 어떻게 찾게되냐 ??
기본값 product_set 으로 찾게된다.

ex ) CategoryObject.product_set.all()

set 은 내가 역참조를 필요할 경우나 many_to_many 가 필요한 경우에 쓰이게 되지 혹시 사용하지 않는다면 굳이 추가할 필요는없다.

참/거짓

  • BooleanField , NullBooleanField

숫자

  • IntegerField
  • SmallIntegerField
  • PositiveIntegerField
  • PositiveSmallIntegerField
  • BigIntegerField
  • DecimalField
  • FloatField

파일

  • BinaryField
  • FileField
  • ImageField
  • FilePathField

이메일

  • EmailField

Relationship Types

  • FireignKey
  • ManyToManyField
  • OneToOneField

makemigrations

makemigrations

python manage.py makemigrations 
데이터베이스 반영할 내용을 찾아서 목록을만든다.

sqlmigrate

python manage.py sqlmigrate shop 001
어떤 쿼리가 실행될지 확인

migrate

python manage.py migrate
반영할 내용을 실제로 반영
profile
꾸준함이란 ... ?

0개의 댓글