- SNS의 간단한 기능 2가지
- 사용자 관리 (회원가입 / 로그인 / 로그아웃)
- 글쓰기
ㅤ- 생성할 APP
- user 앱 : 사용자 관리 ( 회원가입/로그인/로그아웃)을 담당
- tweet 앱 : 글 관리( 글쓰기, 삭제, 수정, 댓글)을 담당
- Django의 Model은 각 Django App안에 기본적으로 생성되는 models.py 모듈 안에 정의하게 된다.
- models.py 모듈 안에 하나 이상의 모델 클래스를 정의할 수 있으며, 하나의 모델 클래스는 데이타베이스에서 하나의 테이블에 해당된다.
장고에는 db 테이블의 필드(= 열(Column))에 매핑될 Model의 클래스 속성들이 아주 많다.
- 우리가 사용할 user model class의 속성들
- 사용자 이름(username) - 비밀번호(password) - 상태정보(bio) - 생성일(created_at) - 수정일(updated_at)
- 메소드 : user model class의 속성들이 db에 저장되는 형태를 정의함
- 문자열 : CharField, TextField - 날짜/시간: DateTimeField, DateField, TimeField - 숫자 : IntegerField, FloatField - 다른 테이블과 연관을 지어 줄 때 : ForeignKey
- user/models.py에 user model class 생성
[user/models.py] from django.db import models # Django의 models 모듈을 models.py에 가져온다. # Create your models here. class UserModel(models.Model): # 'UserModel'이라는 Django의 모델 클래스를 정의 Django의 models 모듈에서 Model 클래스를 상속 받았으니 Django의 ORM기능을 사용하여 DB와 상호작용할 수 있다. class Meta: db_table = "my_user" # 이 모델 클래스의 db에서 테이블 명이 "my_user"이다. username = models.CharField(max_length=20, null=False) # 속성(필드 : 열(column)) = 인스턴스(행(row)) password = models.CharField(max_length=256, null=False) bio = models.CharField(max_length=256, default='') created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)
>>> 위의 모델 클래스에서 'class Meta'는 이 모델의 정보를 담고있다. (db 테이블에 들어갈 정보 : table 이름 = 'my_user')
- tweet/models.py에 tweet model class 생성
[tweet/models.py] from django.db import models from user.models import UserModel # user app의 models.py에서 모델 클래스 UserModel을 가져오겠다. # Create your models here. class TweetModel(models.Model): class Meta: db_table = "tweet" author = models.ForeignKey(UserModel, on_delete=models.CASCADE) # ForeignKey : 다른 데이터베이스에서 '외부 모델을 가져와서 사용하겠다.' : author은 새로운 사람이 아니라 User Model의 사용자가 작성한 글이기 때문 content = models.CharField(max_length=256) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True)