def find_dossier(data):
    '''
    Find dossier with reference matching either 'ref_an' or 'ref_sen',
    create it if not found.  Ensure its reference is 'ref_an' if both fields
    are present.
    '''

    changed = False
    dossier = None
    reffield = None

    for field in [k for k in ('ref_an', 'ref_sen') if k in data]:
        try:
            dossier = Dossier.objects.get(reference=data[field])
            reffield = field
            break
        except Dossier.DoesNotExist:
            pass

    if dossier is None:
        reffield = 'ref_an' if 'ref_an' in data else 'ref_sen'
        dossier = Dossier(reference=data[reffield])
        logger.debug('Created dossier %s' % data[reffield])
        changed = True

    if 'ref_an' in data and reffield != 'ref_an':
        logger.debug('Changed dossier reference to %s' % data['ref_an'])
        dossier.reference = data['ref_an']
        changed = True

    return dossier, changed
Find dossier with reference matching either 'ref_an' or 'ref_sen',
    create it if not found.  Ensure its reference is 'ref_an' if both fields
    are present.