Account Model
Account Models and Utilities
This module defines the core organization unit for the Smarter platform.
This module provides the model and utility functions for managing accounts in the Smarter platform.
It provides the Account model. An account can generically represent any organizational
unit: a company, a course, a team, a department, etc. In the Smarter platform, accounts are used
to group users and resources for RBAC, billing and reporting purposes. This module
also includes helper functions for user resolution and authentication checks.
Classes & Functions
Account: Represents a Smarter account, storing company and billing information.is_authenticated_user(): Checks if an object is an authenticated Django user.get_resolved_user(): Resolves a user-like object to a concrete Django user instance.ResolvedUserType: Type alias for resolved user objects.
Key Features
Enforces unique, validated account numbers.
Supports caching for efficient account retrieval.
Provides utilities for working with Django user objects, including lazy and mock users.
Integrates with Smarter’s logging, configuration, and validation systems.
Example
from smarter.apps.account.models import Account, get_resolved_user
account = Account.objects.create(company_name="Acme Corp")
resolved_user = get_resolved_user(request.user)
if resolved_user and resolved_user.is_authenticated:
print(account.account_number)
- class smarter.apps.account.models.account.Account(*args, **kwargs)[source]
Bases:
MetaDataModelModel representing a Smarter account.
The Account model stores company and billing information, and is the central entity for resource ownership, billing, and user management in the Smarter platform.
- Parameters:
account_number – String. Unique account identifier in the format ‘9999-9999-9999’.
is_default_account – Boolean. Indicates if this is the default account.
company_name – String. Name of the company.
phone_number – String. Company phone number.
address1 – String. Primary address line.
address2 – String. Secondary address line.
city – String. City.
state – String. State or region.
postal_code – String. Postal code.
country – String. Country (default: ‘USA’).
language – String. Language code (default: ‘EN’).
timezone – String. Timezone.
currency – String. Currency code (default: ‘USD’).
is_active – Boolean. If False, account is disabled for billing and resource management.
parent – Account. The account above this one in its organization. Null means directly under the Smarter account, the root of the tree. See
smarter.apps.account.hierarchy.share_scope – Account. This account or one of its ancestors, whose whole subtree may read this account’s resources. Null means that the account shares nothing. The Smarter account always shares with itself, the root, so every account may read its resources.
Example usage:
from smarter.apps.account.models import Account account = Account.objects.create(company_name="Acme Corp") print(account.account_number)
See also
Related models:
UserProfile,AccountContact,Charge- Parameters:
id (Unknown) – Primary key: ID
created_at (Unknown) – Created at
updated_at (Unknown) – Updated at
name (Unknown) – Name. Name in camelCase, e.g., ‘apiKey’, no special characters.
description (Unknown) – Description. A brief description of this resource. Be verbose, but not too verbose.
version (Unknown) – Version. Semantic version in the format MAJOR.MINOR.PATCH, e.g., ‘1.0.0’.
Relationship fields:
- Parameters:
tags (Unknown) – Tags. Tags for categorizing and organizing this resource. (related name:
account)tagged_items (Unknown) – Tagged items (related name:
+)
Reverse relationships:
- Parameters:
children (Unknown) – All children of this Account (related name of
parent)shared_with_subtrees (Unknown) – All shared with subtrees of this Account (related name of
share_scope)contacts (Unknown) – All contacts of this Account (related name of
account)user_profiles (Unknown) – All user profiles of this Account (related name of
account)extensions (Unknown) – All extensions of this Account (related name of
accounts)
- exception DoesNotExist
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned
Bases:
MultipleObjectsReturned
- exception NotUpdated
Bases:
ObjectNotUpdated,DatabaseError
- account_number_format = <django.core.validators.RegexValidator object>
- children
Reverse
ForeignKeyfromAccountAll children of this Account (related name of
parent)- Type:
Type
- contacts
Reverse
ForeignKeyfromAccountContactAll contacts of this Account (related name of
account)- Type:
Type
- created_at
-
Created at
Timestamp indicating when the model instance was created.
This field is automatically set to the current date and time when the instance is first created. It is indexed in the database for efficient querying.
- Type:
Type
- delete(*args, **kwargs)[source]
Delete the account, and forget every account’s readable accounts if it shared its resources.
An account that has children can’t be deleted (
on_delete=PROTECT): move or delete them first.- Returns:
Django’s
(count, per-model counts).
- description
-
Description. A brief description of this resource. Be verbose, but not too verbose.
- Type:
Type
- extensions
Reverse
ManyToManyFieldfromExtensionAll extensions of this Account (related name of
accounts)- Type:
Type
- classmethod get_by_account_number(account_number)[source]
Retrieve an Account instance by its account number.
- Parameters:
account_number – String. The account number to search for.
- Returns:
Optional[Account] The Account instance if found, otherwise None.
- classmethod get_cached_object(*args, invalidate=False, pk=None, name=None, account_number=None, company_name=None, **kwargs)[source]
Retrieve an Account instance by account number with caching.
This method uses caching to optimize retrieval of Account instances by their account number. It checks the cache first and falls back to a database query if the cache is missed.
- Parameters:
invalidate (
bool|None) – If True, invalidate the cache for this query.pk (
int|None) – Optional primary key to search for (ignored if account_number is provided).name (
str|None) – Optional name to search for (ignored if account_number is provided).account_number (
str|None) – String. The account number to search for.company_name (
str|None) – String. The company name to search for (used if account_number is not provided).
- Return type:
- Returns:
Optional[Account] The Account instance if found, otherwise None.
Note
Caching can significantly improve performance for frequently accessed accounts.
Example usage:
account = Account.get_cached_object(account_number="1234-5678-9012") if account: print(account.company_name)
- hierarchy_changed(orig)[source]
Whether a save changes the account tree, or who may read this account’s resources.
- id: int
-
Primary key: ID
The row’s primary key, which Django adds to every concrete model. Declared, without a value, only so that type checkers know it: Django ignores a bare annotation.
- Type:
Type
- invalidate_hierarchy()[source]
Forget every account’s readable accounts, after a change to the tree or to sharing.
- Return type:
- is_active
-
Is active. Indicates whether the account is active. Inactive accounts cannot be used for billing or resource management, nor hosting Provider apis.
- Type:
Type
- is_default_account
-
Is default account. Indicates if this is the default account for the organization. Only one account should be marked as default.
- Type:
Type
- property is_root: bool
Whether this is the Smarter account, the root of the account tree.
- Returns:
True for the Smarter account.
- objects = <django.db.models.Manager object>
- parent
-
Parent. The account above this one in its organization. Null means directly under the Smarter account, the root of the tree. (related name:
children)- Type:
Type
- classmethod randomized_account_number()[source]
Generate a random account number in the format ####-####-####.
This method ensures uniqueness by checking for collisions with existing account numbers.
- Returns:
str A unique account number string.
Note
The generated account number is zero-padded and segmented for readability.
Example usage:
from smarter.apps.account.models import Account account_number = Account.randomized_account_number() print(account_number) # e.g., '1234-5678-9012'
- save(*args, **kwargs)[source]
Save the Account instance, ensuring a valid and unique account number.
If the account number is set to the default value, this method generates a new unique account number. It also validates the account number format before saving.
- Parameters:
args – Positional arguments passed to the parent save method.
kwargs – Keyword arguments passed to the parent save method.
- Raises:
SmarterValueError – If the account number is invalid.
Example usage:
account = Account(company_name="Acme Corp") account.save() # Ensures account_number is unique and valid
-
Share scope. This account or one of its ancestors, whose whole subtree may read this account’s resources. Null means that the account shares nothing. (related name:
shared_with_subtrees)- Type:
Type
Internal field, use
share_scopeinstead.
Reverse
ForeignKeyfromAccountAll shared with subtrees of this Account (related name of
share_scope)- Type:
Type
- tagged_items
Reverse
GenericRelationfromAccountAll + of this tagged item (related name of
tagged_items)- Type:
Type
- tags = <taggit.managers._TaggableManager object>
- updated_at
-
Updated at
Timestamp indicating when the model instance was last updated.
This field is automatically updated to the current date and time whenever the instance is saved. It is indexed in the database for efficient querying.
- Type:
Type
- user_profiles
Reverse
ForeignKeyfromUserProfileAll user profiles of this Account (related name of
account)- Type:
Type
- smarter.apps.account.models.account.get_resolved_user(user)[source]
Resolve and return a Django user object from a user-like instance.
This function maps various Django user subclasses and proxy types (such as SimpleLazyObject) to a concrete User, AbstractUser, or AnonymousUser instance. It is useful for ensuring type safety and correct type annotations when working with user objects in Django.
- Parameters:
user (
User|AbstractUser|AnonymousUser|SimpleLazyObject| _AnyUser) – Union[User, AbstractUser, AnonymousUser, SimpleLazyObject, _AnyUser] The user-like object to resolve.- Return type:
User|AbstractUser|AnonymousUser|None- Returns:
Optional[Union[User, AbstractUser, AnonymousUser]] The resolved user object, or None if input is None.
- Raises:
SmarterConfigurationError – If the input user type is unexpected.
Note
Handles edge cases such as lazy objects and test mocks.
Example usage:
from smarter.apps.account.models import get_resolved_user resolved_user = get_resolved_user(request.user) if resolved_user and resolved_user.is_authenticated: # Safe to access user fields
See also
django.contrib.auth.models.Userdjango.utils.functional.SimpleLazyObject
- smarter.apps.account.models.account.is_authenticated_user(user)[source]
Check if the given user-like object is an authenticated Django user.
This function attempts to determine if the provided object represents an authenticated user by checking for the is_authenticated attribute, which is standard for Django’s User and AnonymousUser models. It also handles edge cases such as lazy objects and test mocks.