组合来自不同应用程序/模型的两个查询,以在单个概述页面上显示它们

时间:2017-03-16 12:57:50

标签: django django-models django-views

我最近才开始使用Django,并且想知道如何组合来自不同应用程序/模型的两个查询并在给定的概述页面中显示它们。我将在下面显示一些非功能性伪代码来说明我想要做的事情:

的index.html

请注意,我在这里添加了两个单独的context_object_names,以说明我要做的事情(latest_newslatest_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]

我看过类似的问题,他们试图将来自同一个应用程序的多个模型的多个查询组合起来(例如 Display objects from different models at the same page according to their published date)但我会很感激任何提示或提示是我描述的情况的“最佳实践”,因为我希望更频繁地结合来自不同应用程序的查询。

1 个答案:

答案 0 :(得分:2)

你根本不想要一个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}

(另请注意,您可以轻松地使用基于函数的视图,因为您并没有从类中获得任何值。)