I am trying to learn some Jinja scripting and got stuck at trying to loop through entities states , using a selectattr filter
I’ve seen this code executed in a YT video, and in some other places, but for me it keeps saying:
UndefinedError: ‘homeassistant.util.read_only_dict.ReadOnlyDict object’ has no attribute ‘device_class’
I absolutely have devices which have attribute device_class which = battery
Can someone please help me “get out of this loop” ?
{% for state in states.sensor | selectattr('attributes.device_class', '==', 'battery') %}
{{state.entity_id}} : {{state.state}}
{% endfor %}
Using ‘selectattr’ with ‘==’ requires that the attribute exists. Some of your sensors do not have a ‘device_class’ attribute, so it fails. You can fix it by including another ‘selectattr’ to just get entities that have it defined…
{% for state in states.sensor | selectattr('attributes.device_class', 'defined') | selectattr('attributes.device_class', '==', 'battery') %}
{{state.entity_id}} : {{state.state}}
{% endfor %}
@michaelblight
Thank you. This made it working for me now.
I thought ‘==’ would filter those out also, but evidently that is not the case.
Is there a different condition operator which kind of combines the two?
Either way, you got me going again. Much appreciated.