You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django模板中获取数据表首列数据?语法报错求助

Django模板获取查询集首条数据的正确方法

问题场景

需要在Django模板中直接获取数据表首条数据的title字段,当前视图代码如下:

def get_table(request):
    table = Table.objects.all()
    return render(request, 'template.html', {'table': table})

尝试在模板中使用{{table|first.title}}时触发TemplateSyntaxError:

TemplateSyntaxError: Could not parse the remainder: '.title' from 'table|first.title' 

数据库表结构及数据:

idtitle
1Testing title
2A really good title

不想通过遍历查询集的方式实现,需要直接获取首条数据的字段值。

解决方法

方法1:修正模板语法

Django模板解析器会把table|first.title误认为是尝试调用名为first.title的过滤器,正确的写法是先通过first过滤器获取首条数据,再访问其属性,有两种实现方式:

方式A:用括号明确解析顺序

{% block 'content' %}
    <h1 class="title">{{ (table|first).title }}</h1>
{% endblock %}

方式B:用with标签暂存首条数据

{% block 'content' %}
    {% with first_item=table|first %}
        <h1 class="title">{{ first_item.title }}</h1>
    {% endwith %}
{% endblock %}

方法2:在视图层直接传递首条数据

更高效的方式是在视图中提前获取首条数据,避免模板中处理查询集:

def get_table(request):
    table = Table.objects.all()
    first_table_item = table.first()  # 也可直接写 Table.objects.first()
    return render(request, 'template.html', {'table': table, 'first_item': first_table_item})

模板中直接使用:

{% block 'content' %}
    <h1 class="title">{{ first_item.title }}</h1>
{% endblock %}

注意:如果查询集为空,first()会返回None,模板中访问None.title会触发AttributeError,可添加判断:

{% if first_item %}
    <h1 class="title">{{ first_item.title }}</h1>
{% else %}
    <h1 class="title">No data available</h1>
{% endif %}

内容的提问来源于stack exchange,提问作者Abdulaziz0

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 05:03:36