TimestampedModel

The abstract base model of every Smarter Django model, with timestamps, hashed ids and caching.

class smarter.lib.django.models.timestamped_model.TimestampedModel(*args, **kwargs)[source]

Abstract base model for all Django models in Smarter, with automatic timestamp fields and utility methods.

This class should be used as the base class for all models in the project to ensure consistent tracking of creation and modification times. It adds created_at and updated_at fields, and provides validation and time-difference utilities.

Example Usage:

from smarter.lib.django.models import TimestampedModel

class MyModel(TimestampedModel):
    name = models.CharField(max_length=100)

# Creating an instance
obj = MyModel.objects.create(name="Example")
print(obj.created_at)  # Timestamp of creation
print(obj.updated_at)  # Timestamp of last update

# Checking elapsed time since last update
seconds = obj.elapsed_updated
print(f"Seconds since last update: {seconds}")

Parameters:

Inherits all parameters from django.db.models.Model.

Note

  • This class is abstract and will not create a database table by itself.

  • The validate() method is a stub and should be implemented in subclasses as needed.

  • The save() method enforces validation before saving, raising a detailed error if validation fails.

Important

  • If you override save(), ensure you call super().save(*args, **kwargs) to retain validation and timestamp behavior.

  • The elapsed_updated property expects updated_at to be set; if not, it returns None.

  • The hashed ID methods provide a way to encode and decode object IDs for use in URLs in cases where you want to avoid exposing raw database IDs.

Parameters:
  • created_at (Unknown) –

    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.

  • updated_at (Unknown) –

    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.

HASH_FLOOR = 1000000
HASH_PREFIX = 'r'
HASH_SUFFIX = 'x'
cache_expiration: ClassVar[int] = 60

Seconds that get_cached_object() caches a row, from smarter_settings.subsystem_cache_expiration.

created_at

DateTimeField

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

property elapsed_updated: int | None

The number of whole seconds since the model’s updated_at timestamp.

It is a property, so it always compares updated_at with the current time: the dt parameter can’t be passed, and is always None. A naive updated_at is compared with the naive current time, and an aware one with the current UTC time.

Example

obj = MyModel.objects.get(pk=1)
seconds = obj.elapsed_updated
print(f"Seconds since last update: {seconds}")
Returns:

The absolute difference in seconds between updated_at and now, or None if updated_at is not set, e.g. because the object has not been saved.

classmethod find_hash(value)[source]

Finds and returns the first url path segment in the given value that is a hashed ID.

A segment counts only if it matches hash_regex() and also decodes to an id, so a path segment that merely looks like one, e.g. rex, is skipped. Pass a url’s path, not the whole url: a host name is never a hashed ID.

Example:

MyModel.find_hash("/workbench/llm-clients/rMTAwMDAyNwx/prompt/")  # "rMTAwMDAyNwx"
MyModel.find_hash("/api/v1/llm-clients/repo-ex/prompt/")  # None
Parameters:

value (str) – The string to search for a hashed ID, usually a url path.

Return type:

str | None

Returns:

The first hashed ID found, otherwise None.

classmethod get_cached_object(invalidate=False, pk=None, **kwargs)[source]

Retrieve a model instance by primary key, using caching to optimize performance.

This method is selectively overridden in models that inherit from TimestampedModel to provide class-specific function parameters.

Example

# Retrieve by primary key
instance = MyModel.get_cached_object(pk=1)
Parameters:
  • invalidate (bool | None) – Whether to drop the cached row, and read it again from the database.

  • pk (int | None) – The primary key of the model instance to retrieve.

  • kwargs – Ignored here; subclasses that override this method use them.

Return type:

Model | None

Returns:

The model instance.

Raises:
classmethod get_cached_objects(invalidate=False, **kwargs)[source]

Return every row of the model.

Subclasses override it with filters, e.g. a user profile, and cache those results. The unfiltered list is not cached: a queryset is lazy, so returning it costs nothing, while caching it would store the whole table in Redis, and refill it after every save.

Example

# Retrieve all instances
instances = MyModel.get_cached_objects()
Parameters:
  • invalidate (bool | None) – Accepted for the subclasses’ signature. Nothing is cached here.

  • kwargs – Ignored here; subclasses that override this method use them.

Return type:

QuerySet[TimestampedModel]

Returns:

A queryset of all model instances.

Raises:

NotImplementedError – if called on an abstract model class.

classmethod get_object_by_locator(locator)[source]

Retrieves an object based on its record locator.

Example:

obj = MyModel.objects.create()
print(obj.id)  # e.g., 123
locator = obj.record_locator # e.g., "mymodel-rc2x"

retrieved_obj = MyModel.get_object_by_locator(locator)
print(type(retrieved_obj))  # Should be <class 'MyModel'>
print(retrieved_obj)  # Should be the same as obj
Parameters:

locator (str) – The record locator string to decode and search for.

Return type:

TimestampedModel | None

Returns:

The model instance if found, otherwise None. A failure to decode or find the object is logged, and returns None. A locator comes from the client, so a locator that doesn’t decode, or whose row doesn’t exist, is a WARNING, not an ERROR.

classmethod hash_regex()[source]

Returns a regex pattern that matches a hashed ID that is a whole url path segment.

The hashed ID format is defined by the HASH_PREFIX and HASH_SUFFIX class attributes, with a base64-encoded string in between. A match must start at the beginning of the string or after a /, and end at the end of the string or before a /. Without these boundaries, the pattern would match inside ordinary words, e.g. repo-ex in the host name repo-explorer.

Example:

pattern = MyModel.hash_regex()
pattern.search("/workbench/llm-clients/rMTAwMDAyNwx/prompt/")  # matches rMTAwMDAyNwx
pattern.search("http://repo-explorer.example.com/")  # None
Return type:

Pattern

Returns:

A regex pattern for matching hashed IDs.

property hashed_id: str[source]

Returns a URL-friendly hashed version of the object’s ID for use in URLs and other contexts where an obscured, non-identifying, non-sequential identifier is preferred.

Encoding scheme:

  1. Take the object’s ID and add a large constant (HASH_FLOOR) to ensure it’s not easily guessable.

  2. Convert the resulting number to a string and encode it using URL-safe base64 encoding.

  3. Remove any padding characters from the encoded string.

  4. Add a prefix and suffix to the encoded string to create a recognizable format.

Example:

obj = MyModel.objects.create()
print(obj.id)  # e.g., 123
print(obj.hashed_id)  # e.g., "rc2x"
Returns:

Hashed ID string (URL-safe, no padding).

id: int

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.

classmethod id_from_hashed_id(hashed_id)[source]

Decodes a hashed ID back to the original object ID.

Decoding scheme:

  1. Validate that the hashed ID starts with the expected prefix and ends with the expected suffix.

  2. Remove the prefix and suffix to isolate the base64-encoded string.

  3. Add padding if necessary to make the length of the encoded string a multiple of 4.

  4. Decode the base64 string to get the original number as a string.

  5. Convert the decoded string to an integer and subtract the HASH_FLOOR to get the original ID.

Example:

my_record = MyModel.objects.create()
print(my_record.id)  # e.g., 123
hashed_id = my_record.hashed_id  # e.g., "rc2x"

original_id = MyModel.id_from_hashed_id(hashed_id)
print(original_id)  # Should print the original ID (e.g., 123)
Parameters:

hashed_id (str) – The hashed ID string to decode (URL-safe, no padding).

Return type:

int | None

Returns:

The original object ID if decoding is successful, otherwise None.

property is_billable_resource: bool

Indicates whether the model instance is considered a billable resource.

This property can be overridden in subclasses to specify which models are billable. By default, it returns False, indicating that the base TimestampedModel is not billable.

Returns:

True if the instance is billable, False otherwise.

property ready: bool[source]

Check if the model instance is ready for use.

Returns:

True if the instance is ready, False otherwise.

property record_locator: str[source]

Returns a short, URL-friendly record locator derived from the object’s ID.

Example:

obj = MyModel.objects.create(name="Example")
print(obj.id)  # e.g., 123
print(obj.record_locator)  # e.g., "llmclient-rc2x"
Returns:

Record locator string (URL-safe, no padding).

save(*args, **kwargs)[source]

Save the model instance to the database, performing validation before the actual save.

This method overrides the default save() behavior of Django models to ensure that the model is validated by calling validate() before any data is written to the database. If validation fails, a django.core.exceptions.ValidationError is raised with detailed information about the error, the arguments passed, the model class, and the current field values.

Example

obj = MyModel(name="Example")
obj.save()  # Will call validate() before saving

Note

  • The validate() method is intended to be overridden in subclasses to provide custom validation logic.

  • If validate() raises a ValidationError, the save operation is aborted and the error is propagated.

  • The error message includes the arguments, keyword arguments, model class, and current field values for easier debugging.

Important

  • If you override this method in a subclass, always call super().save(*args, **kwargs) to retain validation and timestamp functionality.

  • If validation fails, no data will be saved to the database.

Parameters:
  • args – Positional arguments, forwarded to Django’s save().

  • kwargs – Keyword arguments, forwarded to Django’s save().

Raises:

SmarterValueError – if validate() raises any exception. Its message names the model and the row’s primary key, never the field values: a row can hold secrets, and the message reaches logs and api error responses.

to_json()[source]

Serialize the model instance to a JSON-compatible dictionary.

This method uses the custom SmarterJSONEncoder to ensure that all fields, including timestamps and any complex data types, are properly serialized.

Return type:

dict[str, Any]

Returns:

A dictionary representation of the model instance suitable for JSON serialization.

Raises:

SmarterValueError – if the instance can’t be serialized.

updated_at

DateTimeField

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

validate()[source]

Validate the model.

Attention

Intended to be overridden in subclasses to provide custom validation logic.