<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
 def retrieve_layers(self, *args, **options):
 """ Retrieve specified layers or all external layers if no layer specified. """

        # init empty Q object
        queryset = Q()

        # if no layer specified
        if len(args) < 1:
            # cache queryset
            all_layers = Layer.objects.published().external()
            # check if there is any layer to exclude
            if options['exclude']:
                # convert comma separated string in python list, ignore spaces
                exclude_list = options['exclude'].replace(' ', '').split(',')
                # retrieve all layers except the ones specified in exclude list
                return all_layers.exclude(slug__in=exclude_list)
            else:
                # nothing to exclude, retrieve all layers
                self.verbose('no layer specified, will retrieve all layers!')
                return all_layers

        # otherwise loop over args and retrieve each specified layer
        for layer_slug in args:
            queryset = queryset | Q(slug=layer_slug)
            # verify existence
            try:
                # retrieve layer
                layer = Layer.objects.get(slug=layer_slug)
                # raise exception if layer is not external
                if not layer.is_external:
                    raise CommandError('Layer "%s" is not an external layer\n\r' % layer_slug)
                # raise exception if layer is not published
                if not layer.is_published:
                    raise CommandError('Layer "%s" is not published. Why are you trying to work on an unpublished layer?\n\r' % layer_slug)
            # raise exception if one of the layer looked for doesn't exist
            except Layer.DoesNotExist:
                raise CommandError('Layer "%s" does not exist\n\r' % layer_slug)

        # return published external layers
        return Layer.objects.published().external().select_related().filter(queryset)