【问题标题】:Django Object FilterDjango 对象过滤器
【发布时间】:2019-12-27 03:41:03
【问题描述】:

我有一个简单的过滤器,用户可以在其中输入一个字符串term,并将其与本地数据库中的companyId 列进行比较。如果有匹配项,则会在我的模板中的表格中呈现相应的记录。但是,模板中没有呈现任何数据,只有与特定查询的记录数匹配的空字段行。我有类似的逻辑用于显示这些未经过滤的记录,效果很好。

编辑:

当我移除键值并尝试只渲染{{ object }}等对象时,显示如下:(Opportunity: Opportunity object (8)

views.py

def opportunity_dashboard(request):
    try:
        term = request.GET.get('search_query')
        if term:
            filtered_objects = Opportunity.objects.filter(companyId__icontains=term)

filtered_local_zip = zip(filtered_objects)

context = {
    'term': term,
    'filtered_local_zip': filtered_local_zip,
    'filtered_connectwise_zip': filtered_connectwise_zip
}

return render(request, 'website/opportunity_dashboard.html', context)

模板.html

{% if term %}
{% for object in filtered_local_zip %}
<tr>
    <th style="text-align: center;">
        <a href="https://solutions.byteworks.com/new_opportunity/new_opportunity_review?id={{ object.id }}">&#9998;</a>
    </th>
        <td>
            <div class="select">
                <select disabled id="bw_status" name="status">
                    <option value="{{ object.status }}">{{ object.status }}</option>
                </select>
            </div>
        </td>
        <td>
            <a{{ object.opportunityName }}</a>
        </td>
        <td>{{ object.companyId }}</td>
        <td>
            <div class="select">
                <select id="bw_account_manager" name="account_manager">
                    <option value="{{ object.accountManager }}">{{ object.accountManager }}</option>
                </select>
            </div>
        </td>

【问题讨论】:

  • 如果您使用的是python3,请将zip(filtered_objects)替换为list(zip(filtered_objects))
  • @YamanAhlawat 我是,但到目前为止没有列表声明没有任何问题。我进行了更改,但仍然没有呈现数据。比如{{ object.accountManager }},应该有的地方没有值。
  • for object in context.filtered_local_zip 您将上下文作为字典传递。您需要在 dict 上进行迭代或将 forloop 更改为在 context.filtered_local_zip 上进行迭代。
  • 你不需要使用 zip。就做list(filtered_objects)
  • @YamanAhlawat 请查看我的编辑,显然我正在返回一些数据,但只是对数据库对象的描述,而不是记录的实际值

标签: python html django django-models


【解决方案1】:

您不需要 zip()list() 来遍历 Django 模板中的查询集。

只需将其传递给上下文。

filtered_local_zip = filtered_objects

并在模板中迭代它,就像你已经在做的那样:

{% for object in filtered_local_zip %}

如果您需要遍历 zip(),请阅读:https://stackoverflow.com/a/4238261/1307020

这表明了这一点

{% for object0, object1 in filtered_local_zip %}

或者这个

{{ object.0.property }}

演示:https://repl.it/repls/UntidyLimpingCollaborativesoftware

【讨论】:

  • 请查看我对您的评论的回复,这可行,但是我将四个对象传递给我的模板以进行一致的迭代。因此使用zip。如果您有任何想法,我将不胜感激。
  • @t0bi 分别传递所有查询集,在上下文中创建键、值对。如果您不想使用 zip 并单独循环它们
猜你喜欢
  • 2018-08-05
  • 2013-03-16
  • 2014-02-10
  • 2014-05-31
  • 1970-01-01
  • 2017-01-07
  • 1970-01-01
  • 2010-12-07
相关资源
最近更新 更多