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.
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’.
annotations (Unknown) – Annotations. Key-value pairs for annotating this resource.
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:
- exception DoesNotExist
Bases:
ObjectDoesNotExist
- exception MultipleObjectsReturned
Bases:
MultipleObjectsReturned
- exception NotUpdated
Bases:
ObjectNotUpdated,DatabaseError
- account_number_format = <django.core.validators.RegexValidator object>
- 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
- daily_billing_records
Reverse
ForeignKeyfromDailyBillingRecordAll daily billing records of this Account (related name of
account)- Type:
Type
- description
-
Description. A brief description of this resource. Be verbose, but not too verbose.
- 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 (
Optional[bool]) – If True, invalidate the cache for this query.pk (
Optional[int]) – Optional primary key to search for (ignored if account_number is provided).name (
Optional[str]) – Optional name to search for (ignored if account_number is provided).account_number (
Optional[str]) – String. The account number to search for.company_name (
Optional[str]) – 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)
- id
-
Primary key: ID
- Type:
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
- objects = <django.db.models.Manager object>
- 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
- 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 (
Union[User,AbstractUser,AnonymousUser,SimpleLazyObject,object]) – Union[User, AbstractUser, AnonymousUser, SimpleLazyObject, _AnyUser] The user-like object to resolve.- Return type:
Union[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.