backend/django

django tutorial: API 사용해보기 & django admin 사용법 (part2)

seul chan 2017. 3. 2. 14:21

Playing with the API (부터 다시)

$python manage.py shell => Python shell 불러오기

=> 그냥 'python'이라고 치는 대신 shell을 사용하는 이유: DJANGO_SETTINGS_MODULE 환경 변수를 세팅 => mysite/settings.py file에 import 해줌

*만약 manage.py를 사용하지 않으면 DJANGO_SETTINGS_MODULE 환경 변수를 mysite.settings에 세팅하면 된다

>>> import django

>>> django.setup()

----------이렇게 세팅해 주면 됨


explore database API in shell

*이제부터는 뜬 python shell에 써주면 된다

---------------------------

>>>from polls.models import Question, Choice

# 만든 class들을 import 해오기

# 아직 question이 없다

>>>Questions.objects.all()  # 쿼리 세팅

#새 question 만들기

# time zone? 장고는 tzinfo의 put_data에 있는 datetime을 기대한다?? 

>>>from django.utils import timezone

>>>q = Question(

    questoin_text = "What's new?", 

    pub_date = timezone.now()

            )

# object를 데이터베이스에 저장. save()

>>>q.save()


# 이제 q는 ID값을 갖는다 => 데이터베이스에 따라 다름: ex)1 대신 1L이라고

>>q.id

1

#python attribues를 통해 모델 필드에 접근

>>>q.question_text

>>>q.pub_date


# attribute를 변경하여 값을 변경하고, save()로 저장 가능

>>>q.question_text = "What's up?"

>>>q.save()


# objects.all() 명령은 데이터베이스에 있는 모든 questions들을 보여준다

>>>Question.objects.all()

<QuerySet [<Question: Question object>]> #결과값


#위의 결과값은 쓸모없다? Qeustion 모델에 __str__() 메소드를 추가하자

# 이부분은 python의 class, 객체를 더 공부해야 할듯하다

polls/models.py를 다음과 같이 수정해준다.

----------------------

from django.db import models

from django.utils.encoding import python_2_unicode_compatible


@python_2_unicode_compatible  # only if you need to support Python 2

class Question(models.Model):

    # ...

    def __str__(self):

        return self.question_text


@python_2_unicode_compatible  # only if you need to support Python 2

class Choice(models.Model):

    # ...

    def __str__(self):

        return self.choice_text

------------------------

__str__ method를 추가하는 것 

=> interactive prompt를 위한 편의 + 장고의 자동-생성 admin을 통한 객체 (??)

=> normal python method이다.


이제 custom method를 추가해보자. 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)

----------

를 추가한다. 


import datetime/ from django.utils import timezone

=> 파이썬의 스탠다드 datetime 모듈과 장고의 time-zone 유틸리티를 불러옴

(타임존 서포트 독스 참고: https://docs.djangoproject.com/en/1.10/topics/i18n/timezones/)


이제 다시 파이썬 셀을 불러온다

$python manage.py shell

-----------------

>>> from polls.models import Question, Choice

# __str__()이 동작하는지 확인하고

>>> Qeustion.objects.all()

<QuerySet [<Question: What's up?>]> # 이렇게 동작해야 한다.

# 장고는 objects.all() 외에도 다양한 데이터베이스 API를 제공

# 다음과 같이

>>> Question.objects.filter(id=1)

>>> Question.objects.filter(question_text__startswith='What')

# id값이 없으면 예외처리가 된다.


# primary key(id?)가 가장 흔한 케이스기 때문에 장고는=> primary-key lookups의 shortcut을 제공한다.

           

>>> Question.objects.get(pk=1) # Question.objects.get(id=1)을 이렇게 씀

#아까 만든 custom method(was_published_recently)가 작동하는지 보자

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

>>> q.was_published_recently()

True

# Choices를 할수있는 Question을 만들자

=> create는 새로운 Choice object를 만듬

=> 가능한 choices에 Choice object를 추가

# a set to hold the "other side" of a ForeignKey relation

# (e.g. a question's choice) which can be accessed via the API. (무슨말인지 잘...))


# object set과 관련된 모든 choices들을 보여준다.

>>> q.choice_set.all()

# 현재는 아무런 set이 없음을 볼 수 있다. 

           

# 이제 3가지 choice를 만들것이다.           

>>> 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)


# 만들어진 choice objects는 Question objects에 접근할 수 있는 API를 가짐

>>> c.question

           

# 반대도 가능하다

# => Question objects는 Choice objects에 접근 가능           

>>> q.choice_set.all()           

<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>

>>> q.choice_set.count()



# API는 자동으로 당신이 필요한 관계를 따른다

# __ (double underscore) => 관계들을 나눌 때 사용           

                   

# 올해 만들어졌는지를 확인하는 question을 만들어보자

>>> from django.utils import timezone

>>> current_year = timezone.now().year

>>> Question.objects.get(pub_date__year=current_year)

<Question: What's up?>         

# (reusing the 'current_year' variable we created above).

>>> Choice.objects.filter(question__pub_date__year=current_year)

<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>


# Let's delete one of the choices. Use delete() for that.

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

>>> c.delete()

----------------------


Introducing the Django Admin


admin user 만들기

$python manage.py createsuperuser

Username: admin

Email adress: 

password: ******

# admin 대신에 admin에서 사용할 id, password엔 본인의 패스워드를 입력한다. 메일은 왜 입력하는지 잘 모르겠지만 입력하래니깐 입력한다.


admin 서버 접속하기

$python manage.py runserver #서버 동작시키기

localhost:8000/admin/ 을 접속하면 어드민 서버에 접속할 수 있다.


Poll 앱 등록하기
poll 앱을 실행하기 위해서 admin에게 Question objects가 어드민 인터페이스를 갖는다고 애기해줘야함

polls/admin.py 파일을 실행해서

--------------------

from django.contrib import admin

from .models import Question

admin.site.register(Question)

-----------------

를 추가해준다. 


Explore the free admin functionality

Polls 앱의 Questions에 들어가보면 만들어진 What's up을 확인할 수 있다.

- Question 모델로부터 폼이 자동으로 생성

- 모델 타입별(DateTimeField, CharField)에 맞는 HTML 인풋 위젯을 불러줌

- DateTimeField는 Javascript 숏컷을 불러옴.. Today는 달력 팝업을, Now는 시간을 나타내줘 편하게 설정 가능하다

Save – Saves changes and returns to the change-list page for this type of object.

Save and continue editing – Saves changes and reloads the admin page for this object.

Save and add another – Saves changes and loads a new, blank form for this type of object.

Delete – Displays a delete confirmation page.