<Question: Question object (1)>은 이 객체를 표현하는 데 별로 도움이 되지 않습니다. (polls/models.py 파일의) Question 모델을 수정하여, __str__() 메소드를 Question과 Choice에 추가.
<polls/models.py>
from django.db import models
class Question(models.Model):
# ...
def __str__(self):
return self.question_text
class Choice(models.Model):
# ...
def __str__(self):
return self.choice_text
커스텀 메소드 또한 추가
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)
이렇게 model.py 를 완성하였다.
mysite파일에서 다시 python3 manage.py shell 실행
>>> from polls.models import Choice, Question
# Make sure our __str__() addition worked.
>>> Question.objects.all()
<QuerySet [<Question: What's up?>]>
# Django provides a rich database lookup API that's entirely driven by
# keyword arguments.
>>> Question.objects.filter(id=1)
<QuerySet [<Question: What's up?>]>
>>> Question.objects.filter(question_text__startswith='What')
<QuerySet [<Question: What's up?>]>
# Get the question that was published this year.
>>> from django.utils import timezone
>>> current_year = timezone.now().year
>>> Question.objects.get(pub_date__year=current_year)
<Question: What's up?>
# Request an ID that doesn't exist, this will raise an exception.
>>> Question.objects.get(id=2)
Traceback (most recent call last):
...
DoesNotExist: Question matching query does not exist.
# Lookup by a primary key is the most common case, so Django provides a
# shortcut for primary-key exact lookups.
# The following is identical to Question.objects.get(id=1).
>>> Question.objects.get(pk=1)
<Question: What's up?>
# Make sure our custom method worked.
>>> q = Question.objects.get(pk=1)
>>> q.was_published_recently()
True
# Give the Question a couple of Choices. The create call constructs a new
# Choice object, does the INSERT statement, adds the choice to the set
# of available choices and returns the new Choice object. Django creates
# a set to hold the "other side" of a ForeignKey relation
# (e.g. a question's choice) which can be accessed via the API.
>>> q = Question.objects.get(pk=1)
# Display any choices from the related object set -- none so far.
>>> q.choice_set.all()
<QuerySet []>
# Create three choices.
>>> 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 have API access to their related Question objects.
>>> c.question
<Question: What's up?>
# And vice versa: Question objects get access to Choice objects.
>>> q.choice_set.all()
<QuerySet [<Choice: Not much>, <Choice: The sky>, <Choice: Just hacking again>]>
>>> q.choice_set.count()
3
# The API automatically follows relationships as far as you need.
# Use double underscores to separate relationships.
# This works as many levels deep as you want; there's no limit.
# Find all Choices for any question whose pub_date is in this year
# (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()
관리자 생성하기
$ python manage.py createsuperuser
Username: admin
Email address: admin@example.com
Password: **********
Password (again): *********
Superuser created successfully.
개발 서버 시작
$ python manage.py runserver
그 후에 http://127.0.0.1:8000/admin/
로 들어가면 다음과 같이 뜬다.
admin치고 password 1234
그럼 다음과 같이 이미지가 뜬다.
편집 가능한 그룹과 사용자와 같은 몇 종류의 컨텐츠를 볼 수 있습니다. 이것들은 django.contrib.auth 모듈에서 제공되는데, Django 에서 제공되는 인증 프레임워크 입니다.
관리 사이트에서 poll app 을 변경가능하도록 만들기
<polls/admin.py>
from django.contrib import admin
from .models import Question
admin.site.register(Question)
자유로운 관리 기능을 탐색하기
Question 을 등록시켰으니 Django 는 이를 알아채고 관리 인덱스 페이지에 이를 표시할 것
다시 python3 manage.py runserver하면 이렇게 뜹니다.
questions누른다.
이 페이지는 데이터베이스에 저장된 모든 질문들을 보여주며, 그 중 하나를 선택하여 변경할 수 있습니다.
이전에 등록했던 《What’s up?》 질문이 있을 것.
수정 가능.
'Computer Science > Web' 카테고리의 다른 글
[Django] 장고 튜토리얼(4), 간단한 설문조사(Polls) 어플리케이션 (0) | 2021.05.23 |
---|---|
[Django] 장고 튜토리얼(3), 간단한 설문조사(Polls) 어플리케이션 (0) | 2021.05.22 |
[Django] 장고 튜토리얼(2-1), 간단한 설문조사(Polls) 어플리케이션 (0) | 2021.05.19 |
[Django] 장고 튜토리얼(1), 간단한 설문조사(Polls) 어플리케이션 (0) | 2021.05.15 |
[리눅스] 노트북 산 기념 리눅스 환경 만들기! + 장고 설치까지.. (0) | 2021.05.14 |