django_any/models.py
def any_file_field(field, **kwargs):
    """
    Lookup for nearest existing file

    """
    def get_some_file(path):
        subdirs, files = field.storage.listdir(path)

        if files:
            result_file = random.choice(files)
            instance = field.storage.open("%s/%s" % (path, result_file)).file
            return FieldFile(instance, field, result_file)

        for subdir in subdirs:
            result = get_some_file("%s/%s" % (path, subdir))
            if result:
                return result
            
    result = get_some_file(field.upload_to)

    if result is None and not field.null:
        raise TypeError("Can't found file in %s for non nullable FileField" % field.upload_to)
    return result
def any_file_field(field, **kwargs):
    """
    Lookup for nearest existing file

    """
    def get_some_file(path):
        subdirs, files = field.storage.listdir(path)

        if files:
            result_file = random.choice(files)
            instance = field.storage.open("%s/%s" % (path, result_file)).file
            return FieldFile(instance, field, result_file)

        for subdir in subdirs:
            result = get_some_file("%s/%s" % (path, subdir))
            if result:
                return result
            
    result = get_some_file(field.upload_to)

    if result is None and not field.null:
        raise TypeError("Can't found file in %s for non nullable FileField" % field.upload_to)
    return result
Lookup for nearest existing file