저는 최근에야 Django로 작업을 시작했고 다른 애플리케이션 / 모델의 두 쿼리를 결합하여 주어진 개요 페이지에 표시하는 방법이 궁금합니다. 내가하려는 작업을 설명하기 위해 아래에 비 기능적 의사 코드를 표시하겠습니다.
Index.html
context_object_names
내가하려는 작업을 설명하기 위해 여기 에 두 개의 개별 항목을 추가했습니다 ( latest_news
및 latest_enzyme
)
{% extends 'base.html' %}
{% block body %}
<div id="docs-content">
<div class="section" id="s-module-django.db.models.fields">
<div class="page-header text-primary">
<h3 class="info-header-blue-publication-small">Overview</h3>
</div>
<div>
<h3 class="info-header-blue-publication-tiny">Latest news:</h3>
</div>
{% if latest_news %}
{{ latest_news.news_text }}
{% else %}
<p>No recent news.</p>
{% endif %}
<div>
<h3 class="info-header-blue-publication-tiny">Latest enzyme:</h3>
</div>
{% if latest_enzyme %}
<ul>
<li><a href="{% url 'gts:detail' latest_enzyme.id %}">{{ latest_enzyme.barcode }}</a></li>
</ul>
{% else %}
<p>No enzymes are available.</p>
{% endif %}
</div>
</div>
{% endblock %}
Views.py
여기에는 내가 시도했지만 작동하지 않은 방법을 설명하는 주석 처리 된 줄과 get_querysets
내 의도를 설명하기 위해 별도의 두 줄이 포함되어 있습니다 .
from django.shortcuts import render from django.http import
HttpResponse from django.views import generic
from gts.models import Enzymes
from news.models import News
# Create your views here.
class IndexView(generic.ListView):
template_name = 'overview/index.html'
#context_object_name = 'latest_enzyme_news'
#def get_queryset(self):
# latest_enzyme = Enzymes.objects.order_by('-pub_date')[0]
# latest_news = News.objects.order_by('-pub_date')[0]
# return (latest_enzyme, latest_news)
context_object_name = 'latest_enzyme'
def get_queryset(self):
return Enzymes.objects.order_by('-pub_date')[0]
context_object_name = 'latest_news'
def get_queryset(self):
return News.objects.order_by('-pub_date')[0]
동일한 응용 프로그램의 여러 모델 ( 예 : 게시 된 날짜에 따라 동일한 페이지에 다른 모델의 개체 표시) 에서 여러 쿼리를 결합하려고 시도한 유사한 질문을 살펴 보았지만 어떤 힌트 나 팁을 주시면 감사하겠습니다. 다른 응용 프로그램의 쿼리를 더 자주 결합하고자하는 상황에 대한 '모범 사례'입니다.
여기에 ListView가 전혀 필요하지 않습니다. 당신은 물건을 나열하는 것이 아닙니다. 두 개의 개별 항목이 표시됩니다.
대신 표준 TemplateView를 사용하고 get_context_data
원하는 특정 항목을 반환하도록 정의 하십시오.
class IndexView(generic.TemplateView):
template_name = 'overview/index.html'
def get_context_data(self):
latest_enzyme = Enzymes.objects.order_by('-pub_date')[0]
latest_news = News.objects.order_by('-pub_date')[0]
return {'latest_enzyme': latest_enzyme, 'latest_news': latest_news}
(또한 실제로 클래스에서 값을 얻지 못하기 때문에 함수 기반 뷰를 쉽게 사용할 수 있습니다.)
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다