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

dbt中{{ this }}在preview/compile与dbt run下模型名解析不一致

问题现象

使用dbt Web IDE开展开发工作时,{{ this }}内置对象在预览(Preview)、编译(Compile)场景下的解析结果,与执行dbt run构建模型时的结果存在差异:预览/编译场景下{{ this.name }}固定返回值为request,仅执行dbt run构建模型时才能正确解析出实际模型名。

以my_model.sql文件为例,文件内编写如下引用代码:

{{ this.database }}
{{ this.schema }}
{{ this.name }}

在Web IDE中触发预览/编译时,返回结果为:

dev_db
public
request

执行命令dbt run -s my_model构建模型时,运行日志中返回的对应结果为:

dev_db
public
my_model
解决方法

可通过以下两种方式实现预览/编译场景下{{ this }}的解析结果与dbt run一致:

  • 升级dbt Cloud Web IDE至最新版本:2024年起推送的Web IDE正式版本已修复该上下文注入缺陷,升级后预览、编译环节会自动注入当前打开文件对应的模型元数据,{{ this }}全字段返回值与dbt run执行逻辑完全对齐,无需额外修改项目内代码。
  • 若暂不支持升级Web IDE,可通过自定义宏做兼容适配:在项目macros目录下新建覆写宏文件,从当前渲染节点的文件路径提取模型名,替换预览场景下默认的request标识,宏代码参考如下:
{% macro get_this() %}
  {% if execute and model is defined %}
    {{ return(builtins.get_this()) }}
  {% else %}
    {% set current_file = node.get('original_file_path', '') %}
    {% if current_file.endswith('.sql') and '/models/' in current_file %}
      {% set parsed_model_name = current_file.split('/')[-1].replace('.sql', '') %}
      {% set temp_relation = api.Relation.create(
          database=target.database,
          schema=target.schema,
          identifier=parsed_model_name
      ) %}
      {{ return(temp_relation) }}
    {% else %}
      {{ return(builtins.get_this()) }}
    {% endif %}
  {% endif %}
{% endmacro %}

该兼容宏不会干扰正式执行逻辑:dbt run、dbt build等正式执行任务触发时,会自动走dbt原生的this解析流程,不会出现模型名解析错误。配置完成后重新在Web IDE触发预览/编译,{{ this.name }}可正确返回当前模型名即代表配置生效。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 01:27:16