def sort_models(self):
        model_names = [
            table.name for table in self.Base.metadata.sorted_tables if table.name in self.models
        ]
        logger.debug("Unsorted models: %s", model_names)
        model_count = len(model_names)
        swapped = True
        sort_round = 0
        while swapped:
            sort_round += 1
            logger.debug('Sorting round: %d (%s)', sort_round, model_names)
            sorted_models = []
            for i in range(model_count):
                model = self.models[model_names[i]]
                for foreign_model_name in model.foreign_models:
                    if foreign_model_name not in sorted_models:
                        sorted_models.append(foreign_model_name)
                if model.name not in sorted_models:
                    sorted_models.append(model.name)
            if model_names == sorted_models:
                swapped = False
            model_names = sorted_models
        logger.debug("Sorted models: %s (%d rounds)", model_names, sort_round)
        return model_names