모델 수정
이번에는 게시된 날짜와 수정된 날짜를 추가해 보도록 하겠습니다.
Cafe 모델에
published_date
와 modified_date
필드를 추가합니다.- tutorialdjango/mysite/main/models.py
from django.db import models class Cafe(models.Model): name = models.CharField(max_length=50) mainphoto = models.ImageField(blank=True, null=True) published_date = models.DateTimeField(auto_now_add=True) modified_date = models.DateTimeField(auto_now=True) content = models.TextField() def __str__(self): return self.name
DateTimeField
에서 auto_now_add=True
옵션을 주면 모델 개체 생성 시간이 자동으로 저장되고, auto_now=True
옵션은 모델 개체 생성 뿐 아니라 수정 시에도 시간이 자동으로 저장됩니다.다음의
makemigrations
명령어 수행 시 사진과 같이 두가지 선택 사항이 나옵니다.(myvenv)root@goorm:/workspace/컨테이너명/mysite# python manage.py makemigrations
원래 저장되어있던 1~3번 카페의 published_date 값을 정해야 하기 때문입니다.
- 1번은 현재 저장되어 있는 요소들의
published_date
값을 정하는 것
- 2번은
models.py
에 돌아가서published_date
의 기본값을 설정하는 것
우리는 1번 사항을 선택합니다.
그러면 넣을 값을 정하라고 나오는데 default가
timezone.now
즉 현재시간입니다. 그냥 엔터를 치거나 timezone.now
를 입력하고 엔터를 칩니다. 그러면 현재 저장되어 있는 카페들의 published_date
값은 현재 시간으로 저장됩니다.modified_date
의 경우 신경쓰지 않아도 됩니다. 수정 때마다 자동으로 현재 시간이 저장되기 때문입니다.이제
migrate
명령까지 마칩니다.(myvenv)root@goorm:/workspace/컨테이너명/mysite# python manage.py migrate ... Running migrations: Applying_main.0003_auto_20200720_0707.py... OK
날짜 출력
cafelist 페이지에서 cafe들의 생성일, 수정일을 표시해 보겠습니다.
- tutorialdjango/mysite/main/templates/main/cafelist.html
<!DOCTYPE html> <html> <head> <title>cafelist</title> </head> <body> <h1>cafelist</h1> <table> {% for cafe in cafes %} <tr onclick="location.href='/cafelist/{{ cafe.pk }}'"> <td>{{ cafe.name }}</td> <td>{{ cafe.content }}</td> <td>{{ cafe.published_date }}</td> <td>{{ cafe.modified_date }}</td> </tr> {% endfor %} </table> </body> </html>