Managers API Reference
Manager Classes
- class ldaporm.managers.LdapManager[source]
Bases:
objectManager class for direct interactions with LDAP servers.
This class provides methods for connecting, searching, adding, modifying, and deleting LDAP objects, as well as utility methods for authentication and password management. It is intended to be used as the main interface for LDAP-backed Django ORM models.
This class handles connecting to the LDAP server, searching, adding, modifying, and deleting LDAP objects. It also handles authentication and password management.
This class is thread-safe – it will use a different LDAP connection for each thread. This is important because LDAP connections are not thread-safe. If you use the same connection in multiple threads, you will get errors.
- add(obj: Model) None[source]
Add a new object to LDAP.
- Parameters:
obj – The model instance to add.
- all() F[source]
Return the F object for compatibility with Django REST Framework.
- Returns:
The F object, which is iterable and supports pagination.
- authenticate(username: str, password: str) bool[source]
Try to authenticate a username/password vs our LDAP server.
If the user does not exist in LDAP, return False. If the user exists, but the bind fails, return False. Else, return True.
- Parameters:
username – The username to authenticate.
password – The password to authenticate with.
- Returns:
True if authentication is successful, False otherwise.
- connect(key: str, dn: str | None = None, password: str | None = None) None[source]
Set the per-thread LDAP connection object. Used by the @atomic decorator.
- Parameters:
key – Configuration key for the LDAP server.
dn – Optional bind DN.
password – Optional password.
- contribute_to_class(cls, accessor_name) None[source]
Set up the manager for a model class, configuring attributes from model meta.
- Parameters:
cls – The model class.
accessor_name – The attribute name to assign the manager to.
- create(**kwargs) Model[source]
Create and add a new object to LDAP.
- Parameters:
**kwargs – Field values for the new object.
- Returns:
The newly created model instance.
- delete(*args, **kwargs) None[source]
Delete an object that matches the given filters.
Important
We only will delete a single object here to protect against accidentally deleting multiple objects by mistake.
- Parameters:
*args – Positional filter arguments.
**kwargs – Keyword filter arguments.
- Raises:
DoesNotExist – If no objects match the query.
MultipleObjectsReturned – If more than one object matches the query.
- delete_obj(obj: Model) None[source]
Delete a specified object from LDAP.
- Parameters:
obj – The model instance to delete.
- dn(obj: Model) str | None[source]
Compute the distinguished name (DN) for a model instance.
- Parameters:
obj – The model instance.
- Returns:
The DN string, or None if not set.
- exclude(*args, **kwargs) F[source]
Return a QuerySet-like F object with negated filters applied.
- Parameters:
*args – Positional filter arguments.
**kwargs – Keyword filter arguments to negate.
- Returns:
An F object with the negated filters applied.
- filter(*args, **kwargs) F[source]
Return a QuerySet-like F object with the given filters applied.
- Parameters:
*args – Positional filter arguments.
**kwargs – Keyword filter arguments.
- Returns:
An F object with the filters applied.
- get(*args, **kwargs) Model[source]
Return the single result of the query, or raise DoesNotExist/MultipleObjectsReturned. Accepts kwargs for filtering.
- Parameters:
*args – Positional filter arguments.
- Keyword Arguments:
**kwargs – Keyword filter arguments.
- Returns:
The single model instance matching the query.
- Raises:
LdapManager.DoesNotExist – If no object matches the query.
LdapManager.MultipleObjectsReturned – If more than one object matches the query.
- get_by_dn(dn: str) Model[source]
Get an object specifically by its DN. To do this we do a search with the basedn set to the dn of the object, with scope
ldap.SCOPE_BASEand then get all objects that match. This will be either the object we’re looking for, or nothing.- Parameters:
dn – The distinguished name to search for.
- Returns:
The model instance corresponding to the DN.
- Raises:
ValueError – If the DN is not in the model’s basedn.
DoesNotExist – If no object with this DN exists.
MultipleObjectsReturned – If more than one object matches the DN.
- get_dn(pk: str) str[source]
Given a value for an object primary key, return what the dn for that object would look like.
- Parameters:
pk – the value for the primary key for our model
- Returns:
A fully qualified dn.
- get_or_none(*args, **kwargs)[source]
Return the single result of the query, or None if not exactly one found.
- has_connection() bool[source]
Check if the current thread has an active LDAP connection.
- Returns:
True if a connection exists, False otherwise.
- modify(obj: Model, old: Model | None = None) None[source]
Modify an existing LDAP object, updating its attributes as needed.
- Parameters:
obj – The model instance with updated data.
old – The previous model instance data, if available.
- new_connection(key: str = 'read', dn: str | None = None, password: str | None = None) SimpleLDAPObject[source]
Create and return a new LDAP connection object.
- Parameters:
key – Configuration key for the LDAP server.
dn – Optional bind DN.
password – Optional password.
- Returns:
A connected LDAPObject.
- only(*names: str) F[source]
Return a QuerySet-like F object restricted to the given attribute names.
- Parameters:
*names – Attribute names to include in the query.
- Returns:
An F object restricted to the specified attributes.
- Raises:
InvalidField – If any name is not a valid field for the model.
- order_by(*args: str) F[source]
Return a QuerySet-like F object with ordering applied.
- Parameters:
*args – Attribute names to order by (use ‘-’ prefix for descending).
- Returns:
An F object with ordering applied.
- Raises:
InvalidField – If any field is not valid for the model.
- page(page_size: int = 100, cookie: str = '') PagedResultSet[source]
Return a single page of results matching the query.
This method performs a paged LDAP search and returns both the results and metadata needed for pagination.
- Parameters:
page_size – Number of results per page.
cookie – Paging cookie from the previous page (empty string for first page).
- Returns:
A PagedResultSet containing the results and pagination metadata.
- rename(old_dn: str, new_dn: str) None[source]
Rename an object’s DN, keeping it within the same basedn.
- Parameters:
old_dn – The current distinguished name.
new_dn – The new distinguished name.
- reset_password(username: str, new_password: str, attributes: dict[str, Any] | None = None) bool[source]
Reset the password for a user in LDAP.
- Parameters:
username – The username of the user.
new_password – The new password to set.
attributes – Optional additional attributes to update.
- Returns:
True if the password was reset successfully, False otherwise.
- search(searchfilter: str, attributes: list[str], sizelimit: int = 0, basedn: str | None = None, scope: int = 2, sort_control: ServerSideSortControl | None = None) list[tuple[str, dict[str, list[bytes]]]][source]
Search the LDAP server for objects matching the given filter.
- Parameters:
searchfilter – The LDAP search filter string.
attributes – List of attributes to retrieve.
sizelimit – Maximum number of results to return.
basedn – The base DN to search from.
scope – LDAP search scope.
sort_control – Server-side sort control.
- Returns:
List of LDAPData tuples (dn, attrs).
- Raises:
ValueError – If no basedn is provided or configured.
- search_page(searchfilter: str, attributes: list[str], page_size: int = 100, cookie: str = '', sizelimit: int = 0, basedn: str | None = None, scope: int = 2, sort_control: ServerSideSortControl | None = None) tuple[list[tuple[str, dict[str, list[bytes]]]], str][source]
Perform a single page of LDAP search.
This method performs one page of LDAP search using SimplePagedResultsControl and returns both the results and the cookie for the next page.
- Parameters:
searchfilter – The LDAP search filter string.
attributes – List of attributes to retrieve.
page_size – Number of results per page.
cookie – The paging cookie from the previous page (empty string for first page).
sizelimit – Maximum number of results to return.
basedn – The base DN to search from.
scope – LDAP search scope.
sort_control – Server-side sort control.
- Returns:
results: List of LDAPData tuples (dn, attrs)
next_cookie: Cookie for the next page (empty string if no more pages)
- Return type:
Tuple of (results, next_cookie) where
- Raises:
ValueError – If no basedn is provided or configured.
- set_connection(obj: SimpleLDAPObject) None[source]
Set the LDAP connection object for the current thread.
- Parameters:
obj – The LDAPObject to set.
- values(*args: str) list[dict[str, Any]][source]
Return a list of dictionaries representing all objects, with specified attributes.
- Parameters:
*args – Attribute names to include in the dictionaries.
- Returns:
A list of dictionaries, one per object.
- values_list(*args: str, **kwargs) list[tuple[Any, ...]][source]
Return a list of tuples (or namedtuples) representing all objects.
- Parameters:
*args – Attribute names to include in the tuples.
**kwargs – ‘flat’ for single-value tuples, ‘named’ for namedtuples.
- Returns:
A list of tuples or namedtuples, one per object.
- wildcard(name: str, value: str) F[source]
Return a QuerySet-like F object with a wildcard filter applied.
- Parameters:
name – The field name to filter on.
value – The value to filter with wildcards.
- Returns:
An F object with the wildcard filter applied.
- property connection: SimpleLDAPObject
Get the current thread’s LDAP connection object.
- Returns:
The LDAPObject for the current thread.
- class ldaporm.managers.F(manager: LdapManager | None = None, f: F | None = None)[source]
Bases:
objectQuerySet-like class for building LDAP search filters and queries.
This class allows chaining of filter, order, and attribute selection methods to construct LDAP queries in a Django-like fashion.
- Parameters:
manager – The LdapManager instance this query is associated with.
f – An optional F instance to chain from.
- exception NoFilterSpecified[source]
Bases:
ExceptionRaised when no filter is specified for an LDAP search.
- exception UnknownSuffix[source]
Bases:
ExceptionRaised when an unknown filter suffix is used in a query.
- all() F[source]
Return the F object itself for compatibility with Django REST Framework.
- Returns:
The F object itself, which is iterable and supports pagination.
- as_list() list['Model'][source]
Return a list of all objects for this model from LDAP.
- Returns:
A list of all model instances from LDAP.
- bind_manager(manager: LdapManager) None[source]
- count() int[source]
Return the number of objects for this model from LDAP.
- Returns:
The count of all model instances from LDAP.
- delete() None[source]
Delete the object matching the query.
- Raises:
DoesNotExist – If no objects match the query.
MultipleObjectsReturned – If more than one object matches the query.
- exclude(*args, **kwargs) F[source]
Return a new F object with exclude conditions applied.
Exclude conditions are applied as NOT conditions to the final filter. Multiple exclude conditions are combined with AND logic.
- Parameters:
*args – Positional filter arguments (F objects to exclude)
**kwargs – Keyword filter arguments to exclude
- Returns:
A new F object with exclude conditions applied.
Note
Exclude conditions are applied after filter conditions. The final LDAP filter will be: (filter_conditions) AND NOT (exclude_conditions)
- exists() bool[source]
Return True if the query returns any results, False otherwise.
- Returns:
True if any objects match the query, False otherwise.
- first() Model[source]
Return the first result of the query, or raise DoesNotExist if none found.
- Returns:
The first model instance matching the query.
- Raises:
DoesNotExist – If no objects match the query.
- first_or_none(*args, **kwargs) Model | None[source]
Return the first result of the query, or None if no match. Accepts kwargs for filtering.
- get(*args, **kwargs) Model[source]
Return the single result of the query, or raise DoesNotExist/MultipleObjectsReturned. Accepts kwargs for filtering.
- Parameters:
*args – Positional filter arguments.
- Keyword Arguments:
**kwargs – Keyword filter arguments.
- Returns:
The single model instance matching the query.
- Raises:
LdapManager.DoesNotExist – If no object matches the query.
LdapManager.MultipleObjectsReturned – If more than one object matches the query.
- get_or_none(*args, **kwargs) Model | None[source]
Return the single result of the query, or None if not exactly one found. Accepts kwargs for filtering.
- only(*names) F[source]
Restrict the query to only the specified attributes.
- Parameters:
*names – Field names to include in the query.
- Returns:
The F object with restricted attributes.
- Raises:
InvalidField – If any name is not a valid field for the model.
- order_by(*args: str) F[source]
Set the ordering for the query results.
- Parameters:
*args – Field names to order by (use ‘-’ prefix for descending).
- Returns:
The F object with ordering applied.
- Raises:
InvalidField – If any field is not valid for the model.
- page(page_size: int = 100, cookie: str = '') PagedResultSet[source]
Return a single page of results matching the query.
This method performs a paged LDAP search and returns both the results and metadata needed for pagination.
- Parameters:
page_size – Number of results per page.
cookie – Paging cookie from the previous page (empty string for first page).
- Returns:
A PagedResultSet containing the results and pagination metadata.
- update(**kwargs) None[source]
Update the object matching the query with the given attributes.
- Parameters:
**kwargs – Field names and values to update.
- values(*attrs: str) list[dict[str, Any]][source]
Return a list of dictionaries representing the query results.
- Parameters:
*attrs – Field names to include in the dictionaries.
- Returns:
A list of dictionaries, one per object.
- Raises:
NotImplementedError – If .only() was used with .values().
- values_list(*attrs: str, **kwargs) list[tuple[Any, ...]][source]
Return a list of tuples (or namedtuples) representing the query results.
- Parameters:
*attrs – Field names to include in the tuples.
**kwargs – ‘flat’ for single-value tuples, ‘named’ for namedtuples.
- Returns:
A list of tuples or namedtuples, one per object.
- Raises:
NotImplementedError – If .only() was used with .values_list().
ValueError – If flat=True is used with more than one field.
- class ldaporm.managers.Modlist(manager: LdapManager)[source]
Bases:
objectHelper for constructing LDAP modlists for add, update, and delete operations.
- Parameters:
manager – The LdapManager instance this modlist is associated with.
- __init__(manager: LdapManager) None[source]
- add(obj: Model) list[tuple[str, str]][source]
Convert an LDAP DAO object to a modlist suitable for passing to add_s.
- Parameters:
obj – The model instance to add.
- Returns:
The modlist for the add operation.
- Raises:
ImproperlyConfigured – If the object has no objectclasses defined.
- update(new: Model, old: Model, force: bool = False) list[tuple[int, str, None] | tuple[int, str, str] | tuple[str, str]][source]
Build a modlist for updating an LDAP object, using MOD_DELETE or MOD_REPLACE as needed.
- Parameters:
new – The new model instance data.
old – The old model instance data.
force – Whether to force the update even if unchanged.
- Returns:
A list of LDAP modifications to apply to the object.
Decorators
- ldaporm.managers.atomic(key: str = 'read') Callable[source]
Decorator to wrap methods that need to talk to an LDAP server.
- Parameters:
key – Either “read” or “write”. Determines which LDAP server to use.
- Returns:
A decorator that manages LDAP connection context for the wrapped method.
- ldaporm.managers.substitute_pk(func: Callable) Callable[source]
Decorator to allow methods to use the kwarg “pk” as a shortcut for the primary key.
Replaces the “pk” kwarg with the actual primary key field name before calling the method.
- Parameters:
func – The function to wrap.
- Returns:
The wrapped function with pk substitution.
- ldaporm.managers.needs_pk(func: Callable) Callable[source]
Decorator to ensure the primary key attribute is included in LDAP queries.
Ensures that the primary key is present in the attribute list before executing the LDAP search.
- Parameters:
func – The function to wrap.
- Returns:
The wrapped function with primary key enforcement.