Get an image from a random entry I have a section with an text field and an image field. the asset field may sometimes be left blank. in this case, in my template, i want to grab the image from another random entry.

This is the code I'm trying to use, but when the image field is blank in my initial entry, I'm getting an error that Variable "image" doesn't exist.
Am I calling the random image incorrectly?

{% for stat in craft.entries.section('statistics').limit(1).order('RAND()') %}
{% if stat.image|length %}
    {% set image = stat.image.first() %}
{% else %}  
    {% for random in craft.entries.section('statistics').limit(1).image(':notempty:').order('RAND()') %}
        {% set image = random.image.first() %}
    {% endfor %}
{% endif %}

{{ image.url('medium') }}')

{% endfor %}
I think something like this should work

{# First get all the stats #}
{% set stats = craft.entries.section('statistics') %}

{# iterate over those stat in a random order %}
{% for stat in stats.order('RAND()') %}

    {% if stat.image | length %}

        {% set image = stat.image.first %}

    {% else %}

        {# If there's no image, query for a random stat, excluding those without images #}
        {% set randomStat = stats.image(':notempty:').limit(1).order('RAND()') %}
        {% set image = randomStat.first.image.first %}

    {% endif %}

{% endfor %}