'Builds and returns a mapping between attachment IDs and a list of IDs
of the documents whose content contained the attachment URL.'

def attachments_documents_map(self):

    mapping = defaultdict(list)
    documents = Document.admin_objects.exclude(is_redirect=True).only('pk', 'html')
    self.stdout.write(('Attaching    files    to    %s    documents...\n\n' % documents.approx_count()))
    for document in documents.iterator():
        mt_files = DEKI_FILE_URL.findall(document.html)
        kuma_files = KUMA_FILE_URL.findall(document.html)
        params = None
        if mt_files:
            params = models.Q(mindtouch_attachment_id__in=mt_files)
            if kuma_files:
                params = (params | models.Q(id__in=kuma_files))
        if (kuma_files and (not params)):
            params = models.Q(id__in=kuma_files)
        if params:
            attachment_pks = Attachment.objects.filter(params).distinct().values_list('pk', flat=True)
            for attachment_pk in attachment_pks:
                mapping[attachment_pk].append(document.pk)
    return mapping
