Getting "'dict object' has no attribute 'nodes'" error trying to use graph.nodes.values()

Hello,

I attempted to use the macro detailed here in order to find all models with a certain tag and append them into a list.

I created this macro:

{% macro get_models_with_tag(tag) %}

{% set models_with_tag = [] %}
{% for model in graph.nodes.values() | selectattr("resource_type", "equalto", "model") %}

    {% if tag in model.config.tags %}
        {{ models_with_tag.append(model.name) }}
    {% endif %}

{% endfor %}

{{ return(models_with_tag) }}

{% endmacro %}

And I call it in a model like this:

{% set my_project_models = get_models_with_tag('my_tag') %}

{% for model in my_project_models %}

    select *
    from {{ ref(model) }}

    {% if not loop.last %}
        union all
    {% endif %}

{% endfor %}

The purpose is to find all models with a certain tag and then loop through to create a union all of all of these models together to create a final table. However, I end up with a “dict object has no attribute nodes” error. Can someone assist? I’m not sure what I’m doing wrong.

Try encapsulating the logic inside a {% if execute %} statement, something like

{% macro get_models_with_tag(tag) %}

{% if execute %}
{% set models_with_tag = [] %}
{% for model in graph.nodes.values() | selectattr("resource_type", "equalto", "model") %}

    {% if tag in model.config.tags %}
        {{ models_with_tag.append(model.name) }}
    {% endif %}

{% endfor %}

{{ return(models_with_tag) }}

{% endif %}

{% endmacro %}

The reason for that i written here About graph context variable | dbt Developer Hub

The model entries in the graph dictionary will be incomplete or incorrect during parsing. If accessing the models in your project via the graph variable, be sure to use the execute flag to ensure that this code only executes at run-time and not at parse-time.

1 Like

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.