Django 데이터베이스 내용 출력하기

1 개념[ | ]

Django 데이터베이스 내용 출력하기
  • 데이터베이스 내용 쿼리 후 페이지에 출력하기.

2 데이터베이스 정보 확인[ | ]

  • 1. "python manage.py shell" 명령은 쉘을 실행해준다.
  • 2. "from polls.models import Question" 명령은 Question 모델을 import 한다.
  • 3. "Question.objects.all()"은 Question의 모든 객체를 쿼리 해온다.
(DJANGO) johnjeong@zetawiki:~/DJANGO/mysite$ python manage.py shell
Python 3.5.2 (default, Nov 17 2016, 17:05:23) 
[GCC 5.4.0 20160609] on linux
Type "help", "copyright", "credits" or "license" for more information.
(InteractiveConsole)
>>> from polls.models import Question
>>> Question.objects.all()
<QuerySet [<Question: Question object>, <Question: Question object>]>
→ Question object가 두 개 존재하는 것을 알 수 있음

3 데이터베이스 정보 쿼리[ | ]

  • views.py 에서 데이터베이스 내용을 쿼리
#polls/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from .models import Question

def index(request):
	latest_question_list = Question.objects.order_by('-pub_date')[0:5] #Question의 pub_date 열을 가져옴
	template = loader.get_template('polls/index.html') # polls/index.html 템플릿을 가져옴
	context = { # 템플릿안에 latest_question_list를 찾아 실제 값을 넣어줌 
		'latest_question_list' : latest_question_list,
	}
	return HttpResponse(template.render(context, request)) # 출력
  • views.py 에서 데이터베이스 내용을 쿼리 (render를 사용 할 경우)
#polls/views.py
from django.shortcuts import render
from django.http import HttpResponse
from django.template import loader
from .models import Question

def index(request):
    latest_question_list = Question.objects.order_by('-pub_date')[0:5]
    context = {
        'latest_question_list':latest_question_list,
    }
    return render(request, 'polls/index.html', context)

4 템플릿[ | ]

<!--polls/templates/polls/index.html-->
{% if latest_question_list %}
	<ul>
	{% for question in latest_question_list %}
		<li><a href="{% url 'polls:detail' question.id %}">{{ question.question_text }}</a></li>
	{% endfor %}
	</ul>
{% else %}
	<p>No polls are available.</p>
{% endif %}

5 출력 하기[ | ]

6 같이 보기[ | ]

7 참고[ | ]

문서 댓글 ({{ doc_comments.length }})
{{ comment.name }} {{ comment.created | snstime }}