如何在 DBT 中使用 Jinja 遍历所有列?

How do I loop through alll columns using Jinja in DBT?

我想使用 dbt 遍历所有列。

我认为 dbt-utils 包中的 star 宏 + 一些 for-loop 逻辑可能对您有所帮助?这取决于您使用的确切用例和仓库(如评论中所指出)。

star macro 在提供的table 中生成列列表。

所以一个可能的方法是:

{% for col in [{{ dbt_utils.star(ref('my_model')) }}] %}
...operation...
{% endfor %}

您可以使用内置的 adapter 包装器和 adapter.get_columns_in_relation:

{% for col in adapter.get_columns_in_relation(ref('<<your model>>')) -%}
    ... {{ col.column }} ...
{% endfor %}

如果您有 model 节点,并且您有定义为 model properties 的列,这将起作用:

{% for col in model.columns.values() %}
  ... {{ col.name }}  ... {{ col.data_type }} ... 
{% endfor %}

您可以从 graph:

中获取模型节点
{% set model = graph.nodes.values()
        | selectattr("resource_type", "equalto", "model")
        | selectattr("name", "equalto", model_name)
        | first %}