<pre>
    try:
        device = Device.objects.get(id=device_id)
    except Device.DoesNotExist:
        pass
    else:
        for d_id, in Device.objects.get(
                id=device_id,
            ).child_set.values_list('id'):
            if d_id in visited:
                # Make sure we don't do the same device twice.
                continue
            visited.add(d_id)
            stack.append(d_id)
</pre>