Django ORM 다루기 연습문제(2회차)

송용진·2024년 4월 1일

연습문제 1

Question 모델의 pk=2를 가진 객체를 가져오는 Django 쿼리를 작성하세요.

Question.objects.get(pk=2)

연습문제 2

Question 인스턴스의 was_published_recently() 메서드가 False를 반환하는지 확인하는 코드를 작성하세요.

class Question(models.Model):
    #...
    def was_published_recently(self):
        return self.pub_date >= timezone.now() - datetime.timedelta(days=1)

q = Question.objects.get(pk=1)
q.was_published_recently()
False

연습문제 3

Question 인스턴스에 새로운 Choice 객체를 추가하지 않고,
현재 관련된 모든 Choice 객체를 표시하는 코드를 작성하세요.

q = Question.objects.get(pk=1)
q.choice_set.all()

연습문제 4

"Nothing really"라는 choice_text를 가지고
votes가 10인 새 Choice 객체를 생성하는 코드를 작성하세요.

q = Question.objects.get(pk=1)
q.choice_set.create(choice_text="Nothing really", votes=10)

연습문제 5

모든 Question 객체에 연결된
Choice 객체의 총 개수를 반환하는 코드를 작성하세요.

q = Question.objects.get(pk=1)
q.choice_set.count() #1

연습문제 6

Question 모델의 pub_date가 현재 연도인
모든 Choice 객체를 찾는 코드를 작성하세요.
여기서 current_year는 현재 연도를 나타내는 변수입니다.

current_year = datetime.datetime.now().year
Choice.objects.filter(question__pub_date__year=current_year)

datetime 모듈의
datetime 클래스의
now() 메서드의
year 속성

#...datetime 클래스
@property
    def year(self):
        "Return the year."
        return self._year

    @property
    def month(self):
        "Return the month."
        return self._month
 #...

연습문제 7

choice_text가 "Just hacking again"으로 시작하는
모든 Choice 객체를 삭제하는 코드를 작성하세요.

c = q.choice_set.filter(choice_text__startswith="Just hacking again")
c.delete()

연습문제 8

Choice 객체 중
votes가 0인 객체만 필터링하는 Django 쿼리를 작성하세요.

c = Choice.objects.filter(votes=0)
c
#<QuerySet [<Choice: Choice object (1)>]>

연습문제 9

Question 객체 중
pub_date가 2023년 1월 1일 이후인 모든 객체를 가져오는 Django 쿼리를 작성하세요.

from datetime import datetime
Question.objects.filter(pub_date__gte=datetime(2023, 1, 1))

Django의 쿼리셋(QuerySet)에서 gte는
"Greater Than or Equal to"의 약자로,
특정 필드의 값이 주어진 값보다 크거나 같은 레코드를 검색하는데 사용

연습문제 10

Choice 객체 중
questionpub_date가 현재 날짜보다 이전인 모든 객체를 가져오는 Django 쿼리를 작성하세요. 여기서 current_date는 현재 날짜를 나타내는 변수입니다.

from django.utils import timezone
current_date = timezone.now()
Choice.objects.filter(question__pub_date__lt=current_date)
datetime.now()
#datetime.datetime(2024, 4, 1, 23, 33, 8, 42637)
timezone.now()
#datetime.datetime(2024, 4, 1, 14, 33, 15, 113669, tzinfo=datetime.timezone.utc)

Django에서는 timezone.now()를 사용하여 일관된 시간 관리를 유지하는 것이 좋음

profile
개발자

0개의 댓글