갈루아의 반서재

Playing with the API


단순히 "python"이라고 입력하는 대신에, 앞으로는 아래와 같이 사용할 것이다.왜냐하면 manage.py 가DJANGO_SETTINGS_MODULE 환경변수(mysite/settings.py file 의 경로를 가져온다)를 설정해주는 역할을 하기 때문이다.


$ python manage.py shell

아래와 같이 DJANGO_SETTINGS_MODULE 환경 변수를 직접 설정하는 방법도 있다.

>>> import django
>>> django.setup()

manage.py 파일이 위치한 디렉토리에서 파이썬을 실행해야 한다.

더욱 자세한 내용은 django-admin 문서에서 확인가능하다.

이제 그러면 데이터베이스 API 를 살펴보자.





# 방금 작성한 모델 클래스를 가져온다

>>> from polls.models import Question, Choice  

# No questions are in the system yet.
>>> Question.objects.all()
[]

# 새로운 질문을 생성한다

>>> from django.utils import timezone
>>> q = Question(question_text="What's new?", pub_date=timezone.now())

# 해당 오브젝트를 데이터베이스에 저장한다

>>> q.save()

# ID 확인
>>> q.id
1


# 필드값 확인

>>> q.question_text
"What's new?"
>>> q.pub_date
datetime.datetime(2012, 2, 26, 13, 0, 0, 775217, tzinfo=<UTC>)

# 필드값 수정

>>> q.question_text = "What's up?"
>>> q.save()

# 데이터베이스의 모든 질문 확인

>>> Question.objects.all()
[<Question: Question object>]

Question 과 Choice 모델에 __str__() 메서드 추가 


polls/models.py

from django.db import models


class Question(models.Model):
    # ...
    def __str__(self):              # __unicode__ on Python 2
        return self.question_text

class Choice(models.Model):
    # ...
    def __str__(self):              # __unicode__ on Python 2
        return self.choice_text

Python 3 에서는 __str__() 을 사용하면 되고, Python 2 에서는 __unicode__() 메서드 사용한다.


polls/models.py

import datetime

from django.db import models
from django.utils import timezone


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

변경사항을 저장하고 다시 python manage.py shell 실행
>>> from polls.models import Question, Choice


# __str__() 이 제대로 추가되었는지 확인해보자.
>>> Question.objects.all()
[<Question: What's up?>]


# Django는 리치 데이터베이스 검색 API를 지원한다.
>>> Question.objects.filter(id=1)
[<Question: What's up?>]
>>> Question.objects.filter(question_text__startswith='What')
[<Question: What's up?>]

# 올해 추가된 질문을 검색해보자

>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)

<Question: What's up?>


# 존재하지 않는 ID 검색

>>> Question.objects.get(id=2)
Traceback (most recent call last):
    ...
DoesNotExist: Question matching query does not exist.

PK 로 검색하기
>>> Question.objects.get(pk=1)
<Question: What's up?>


# 커스톰 메서드 동작 여부 확인

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

True


# 보기 내용 확인

>>> q = Question.objects.get(pk=1)

>>> q.choice_set.all()
[]

# 세 가지 보기 생성

>>> q.choice_set.create(choice_text='Not much', votes=0)
<Choice: Not much>
>>> q.choice_set.create(choice_text='The sky', votes=0)
<Choice: The sky>
>>> c = q.choice_set.create(choice_text='Just hacking again', votes=0)

# 관련 질문 오브젝트 조회

>>> c.question
<Question: What's up?>

# 관련 보기 오브젝트 조회

>>> q.choice_set.all()
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]
>>> q.choice_set.count()
3

# 올해 생성된 문제의 보기 전부 조회(위에서 생성한 'current_year' 변수 재사용)

>>> Choice.objects.filter(question__pub_date__year=current_year)
[<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]

# 보기 하나를 지운다

>>> c = q.choice_set.filter(choice_text__startswith='Just hacking')
>>> c.delete()


좀 더 자세한 내용은 아래 링크 참조 

모델 관계 : https://docs.djangoproject.com/en/1.8/ref/models/relations/

더블 언더스코어 사용법 : https://docs.djangoproject.com/en/1.8/topics/db/queries/#field-lookups-intro

데이터베이스 API : https://docs.djangoproject.com/en/1.8/topics/db/queries/