在ListView中使用`get_context_data`过滤结果 - python

在我的ListView中,我想从发布模型中返回对象的整个列表,并从预算模型中返回total,以将其包含在ListView中,并带有每个标题和相关的总计。

我的模特:

出版应用

class Publication(models.Model):
      title = models.CharField(...)

预算应用

class Budget(models.Model):
      total = models.DecimalField(...)
      publication = models.ForeignKey(Publication, ...)

观看次数:
出版应用

class PublicationListView(ListView):
      context_object_name = 'publications'
      model = Publication

      def get_context_data(self, **kwargs):
          context = super(PublicationListView, self).get_context_data(**kwargs)

          context['publication'] = self.get_queryset()
          context['budget'] = Budget.objects.all()

          return context

模板:
出版应用

<tbody>
   {% for pub in publications %}
    <tr>
        <td><a href="{{ pub.pk }}">{{ pub.title }}</a>
            <span class="float-right">
                 {% for obj in budget %}
                     {{obj}}
                 {% endfor %}
            </span>
        </td>
    </tr>
   {% endfor %}
</tbody>

在我的模板中,我收到的结果看起来像这样:

publication 1               1000 2000 3000
publication 2               1000 2000 3000
publication 3               1000 2000 3000

但是我需要的是:

publication 1               1000
publication 2               2000
publication 3               3000

我理解为什么我要返回每一行中的所有预算对象,但是我不确定如何仅在关联的出版物中显示正确的预算。

是使用get_context_data()的最佳选择吗?

参考方案

感谢@HakenLid和@WillemVanOnsem的指导,以下是更新的视图和模板,以实现所需的输出

视图

class PublicationListView(ListView):
      context_object_name = 'publications'
      model = Publication

模板

<tbody>
   {% for pub in publications %}
    <tr>
        <td><a href="{{ pub.pk }}">{{ pub.title }}</a>
            <span class="float-right">
                 {% for budget in pub.budget_set.all %}
                     {{ budget }}
                 {% endfor %}
            </span>
        </td>
    </tr>
   {% endfor %}
</tbody>

.get()之后,多处理陷入困境 - python

我试图了解multiprocessing如何在python中工作并遇到一些问题。这是示例:import multiprocessing def func(): return 1 p = multiprocessing.Pool() result = p.apply_async(func).get() 调用.get()函数时,代码只是卡住了。我究竟做错了什么?…

从Azure Data Factory执行python脚本 - python

有人可以帮我从Azure数据工厂执行python函数吗?我已经将python函数存储在blob中,并且我试图触发同样的功能。但是我无法做到这一点。请协助。第二,我可以从ADF参数化python函数调用吗? python参考方案 您可能会发现ADF中的Azure Function Activity概念,它允许您在Data Factory管道中运行Azure F…

将数据直接从Python导出到Tableau - python

我有一个将数据导出到csv中的python代码,然后将该csv加载到Tableau中。我不想将csv加载到tableau中。有没有一种方法可以将我的python脚本的return值直接放入tableau中?问题类似于Export data from Python into Tableau using JSON?,但他们询问Json格式,答案是使用csv。如果…

Flask-从request.get_json()获取键值 - python

我试图从ajax POST请求json数据后获取键值。我成功检索了数据,但是出现错误:“ AttributeError:'unicode'对象没有属性'keys'”。我曾尝试使用json.load(data),但这也没有成功。@app.route('/sendstats', methods=['GET', '…

登录节点如何与Slurm群集中的计算节点通信? - python

我只是开始使用随Slurm Workload Manager运行的计算集群。我对计算节点在计算时如何与登录节点通信感到好奇,因为要运行的脚本与该脚本可能读取的其他文件一起存储在登录节点中。例如,在工作词典中,浮点列表以可以用pickle加载的格式存储。我希望在计算节点上运行的脚本如下所示:import pickle with open('data_…