티스토리 뷰

  ● 포스트 모델링  

 

helpers/models.py

- abstract = True 를 설정하여 이 BaseModel이 추상 모델 클래스이라는 것을 명시한다. 

- 추상 모델 클래스는 여러 개의 모델 클래스들이 공통적인 정보를 가지도록 설정할 때에 사용한다. 추상 클래스는 DB에 테이블을 생성하지 않는다. 다만, 추상 클래스를 상속받는 자식 클래스의 테이블에 추가된다. 

from django.db import models

class BaseModel(models.Model):
    created_at = models.DateTimeField(auto_now_add = True)
    modified_at = models.DateTimeField(auto_now = True)

    class Meta:
        abstract = True

 

- makemigrations migrate 을 실행해도 'No changes detected in app' 'No migrations to apply' 의 결과가 나온다. 이 것은 추상클래스가 데이터베이스에 테이블을 추가하지 않는다는 것을 다시 확인할 수 있다.

python manage.py makemigrations helpers
python manage.py migrate helpers

 

 

 

 

post/models.py

- 게시글에 대한 객체를 모델링한다. 여기서 BaseModel을 상속받았기 때문에 BaseModel 의 'created_at' 'modified_at' 두 개의 필드가 추가된다.

 

- user 필드는 User 모델에서 값을 가져와야하기 때문에 외래키 사용한다.

 

- title은 필수로 입력해야하는 필드이므로 blank = False 으로 설정한다. blank  값은 나중에 정보에 대해서 유효성 검사할 때 제목 필드가 빈칸인 것을 허용하지 않겠다는 뜻이 된다.

 

- 반면, image 는 blank = True으로 유효성 검사 시 빈칸을 허용한다. null은 DB와 관련되어있다. null = True 라는 것은, 데이터베이스에서 값이 NULL 값을 가질 수 있도록 한다.

 

- likes 는 좋아요 버튼 필드이다. 한 사람이 여러 게시물에 좋아요를 누를 수 있고, 한 게시물에 여러 개의 좋아요가 생길 수 있으니 ManyToManyField를 사용한다.

 

- tags는 게시물에 대한 태그 필드이다. "django 커뮤니티" 프로젝트에서 사용한 tag app을 직접 만들었고, 이번에는 TaggableManager 를 사용한다.

from django.db import models
from taggit.managers import TaggableManager
from helpers.models import BaseModel
from user.models import User


class Post(BaseModel):
    user = models.ForeignKey(User, on_delete = models.CASCADE)
    title = models.CharField(max_length=64, blank = False)
    content = models.TextField()
    image = models.ImageField(blank=True, null = True)
    likes = models.ManyToManyField(User, related_name = 'likes', blank = True)
    tags = TaggableManager()

    def __str__(self):
        return '%s - %s' %(self.id, self. title)

    def total_likes(self):
        return self.likes.count()

 

 

 

django_blog/settings.py

- TaggableManager를 사용하기 위해서는 INSTALLED_APPS 에 'taggit'을 추가해야한다.

INSTALLED_APPS += [
    'user',
    'post',
    'helpers',
    'taggit'
]

- taggit을 추가하기 위해서는 django-taggit 패키지를 설치해야한다.

pip install django-taggit
댓글