데이터 분석 기술 블로그

Django에 대하여(14)_ORM with view(Read) 본문

백엔드

Django에 대하여(14)_ORM with view(Read)

데이터분석가 이채은 2024. 4. 4. 09:00

1. Read

1-1 전체 게시글 조회

# articles/views.py

from .models import Article

def index(request):
    articles = Article.objects.all()
    context = {
        'articles': articles,
    }
    return render(request, 'articles/index.html', context)
<!-- articles/index.html -->

<h1>Articles</h1>
<hr>
{% for article in articles %}
  <p>글 번호: {{ article.pk }}</p>
  <p>글 제목: {{article.title }}</p>
  <p>글 내용: {{article.content }}</p>
  <hr>
{% endfor %}

결과

 

1-2. 단일 게시글 조회

# articles/urls.py

urlpatterns = [
    ...
    path('<int:pk>/', views.detail, name='detail'),
]
# articles/views.py

def detail(request, pk):
    article = Article.objects.get(pk=pk)
    context = {
        'articles': articles,
    }
    return render(request, 'articles/detail.html', context)
<!-- templates/articles/detail.html -->

<h2>DETAIL</h2>
<h3>{{ articles.pk }} 번째 글</h3>
<hr>
<p>제목: {{article.title }}</p>
<p>내용: {{article.content }}</p>
<p>작성일: {{ article.created_at }}</p>
<p>수정일: {{ article.updated_at }}</p>
<hr>
<a href="{% url 'articles:index' %}">[back]</a>

결과

 

1-3. 단일 게시글 페이지 링크 작성

<!-- templates/articles/detail.html -->

<h1>Articles</h1>
<hr>
{% for article in articles %}
  <p>글 번호: {{ article.pk }}</p>
  <a href="{% url 'articles:detail' article.pk %}
    <p>글 제목: {{article.title }}</p>
  </a>
  <p>글 내용: {{article.content }}</p>
  <hr>
{% endfor %}