def check_for_territories(query):
    if not query or not current_app.config.get('ACTIVATE_TERRITORIES'):
        return []
    dbqs = db.Q()
    query = query.lower()
    is_digit = query.isdigit()
    query_length = len(query)
    for level in current_app.config.get('HANDLED_LEVELS'):
        if level == 'country':
            continue
        q = db.Q(level=level)
        if (query_length == 2 and level == 'fr:departement' and
                (is_digit or query in ('2a', '2b'))):
            q &= db.Q(code=query)
        elif query_length == 3 and level == 'fr:departement' and is_digit:
            q &= db.Q(code=query)
        elif query_length == 5 and level == 'fr:commune' and (
                is_digit or query.startswith('2a') or query.startswith('2b')):
            q &= db.Q(code=query) | db.Q(keys__postal__contains=query)
        elif query_length >= 4:
            q &= db.Q(name__istartswith=query) | db.Q(name__iexact=query)
        else:
            continue
        dbqs |= q
    if dbqs.empty:
        return []
    return GeoZone.objects(dbqs).order_by('-population', '-area')