본문 바로가기

[내일배움캠프]스파르타코딩클럽 AI 웹개발/Today I Learned

[TIL] models.py 코드 리팩토링

수정전 코드

from django.db import models
from django.conf import settings


# Create your models here.
class Post(models.Model):
    title = models.CharField(max_length=50)
    content = models.TextField()
    created_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)

    image = models.ImageField(
        upload_to="images/",
        blank=True,  # 이미지는 필수가 아님
        # null=True
    )

    author = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="posts"
    )


    def __str__(self):
        return self.title


class Comment(models.Model):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments")
    content = models.CharField(max_length=300)
    created_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now = True)

    def __str__(self):
        return self.content

 

 

 

Post 클래스와 Comment 클래스에 공통으로 있는 created_time과 update_time을 하나의 클래스로 정의한 후

DateTimeModel을 상속받도록 코드를 수정하였다

 

 

 

 

수정후 코드

from django.db import models
from django.conf import settings


# Create your models here.

class DateTimeModel(models.Model):
    created_time = models.DateTimeField(auto_now_add=True)
    updated_time = models.DateTimeField(auto_now=True)

    class Meta:
        abstract = True


class Post(DateTimeModel):
    title = models.CharField(max_length=50)
    content = models.TextField()
    image = models.ImageField(
        upload_to="images/",
        blank=True,  # 이미지는 필수가 아님
        # null=True
    )

    author = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="posts"
    )

    def __str__(self):
        return self.title


class Comment(DateTimeModel):
    post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name="comments")
    content = models.CharField(max_length=300)

    def __str__(self):
        return self.content

'[내일배움캠프]스파르타코딩클럽 AI 웹개발 > Today I Learned' 카테고리의 다른 글

[TIL]  (0) 2024.08.26
[TIL]  (0) 2024.08.25
[TIL]  (0) 2024.08.21
[TIL]  (0) 2024.08.20
[TIL]  (0) 2024.08.19