def query_as_ldap(query, compiler, connection):
    """Convert a django.db.models.sql.query.Query to a LdapLookup."""
    if query.is_empty():
        return

    if query.model._meta.model_name == 'migration' and not hasattr(query.model, 'object_classes'):
        # FIXME(rbarrois): Support migrations
        return

    # FIXME(rbarrois): this could be an extra Where clause
    filterstr = ''.join(['(objectClass=%s)' % cls for cls in
                         query.model.object_classes])

    # FIXME(rbarrois): Remove this code as part of #101
    if (len(query.where.children) == 1
            and not isinstance(query.where.children[0], WhereNode)
            and query.where.children[0].lhs.target.column == 'dn'):

        lookup = query.where.children[0]
        if lookup.lookup_name != 'exact':
            raise LdapDBError("Unsupported dn lookup: %s" % lookup.lookup_name)

        return LdapLookup(
            base=lookup.rhs,
            scope=ldap.SCOPE_BASE,
            filterstr='(&%s)' % filterstr,
        )

    sql, params = compiler.compile(query.where)
    if sql:
        filterstr += '(%s)' % (sql % tuple(escape_ldap_filter(param) for param in params))
    return LdapLookup(
        base=query.model.base_dn,
        scope=query.model.search_scope,
        filterstr='(&%s)' % filterstr,
    )
Convert a django.db.models.sql.query.Query to a LdapLookup.