Models

Model classes provide the interface for working with API resources.

Synchronous Models

class django_api_orm.base.APIModel(**kwargs)[source]

Bases: object

Base class for API models.

Provides Django ORM-like interface for working with API resources. Must be subclassed with _schema_class and _endpoint defined.

Example

>>> class PolicySchema(BaseModel):
...     id: int
...     policy_number: str
...     premium_amount: float
>>>
>>> class Policy(APIModel):
...     _schema_class = PolicySchema
...     _endpoint = "/api/v1/policies/"
>>>
>>> # Register with client
>>> Policy.objects = Manager(Policy, client)
objects: Manager[APIModel]
__init__(**kwargs)[source]

Initialize model instance.

Parameters:

**kwargs (Any) – Field values or _pydantic_instance

__setattr__(name, value)[source]

Set attribute and update internal pydantic instance.

Parameters:
  • name (str) – Attribute name

  • value (Any) – Attribute value

classmethod get_endpoint()[source]

Get the API endpoint for this model.

Returns:

API endpoint path

Return type:

str

classmethod get_schema_class()[source]

Get the Pydantic schema class for this model.

Returns:

Pydantic BaseModel class

Return type:

type[BaseModel]

classmethod from_api(data, client=None)[source]

Create model instance from API response data.

Parameters:
Returns:

Model instance

Return type:

APIModel

to_dict(exclude_unset=False, exclude_none=False)[source]

Convert model to dictionary.

Parameters:
  • exclude_unset (bool) – Exclude fields that weren’t explicitly set

  • exclude_none (bool) – Exclude fields with None values

Returns:

Dictionary representation

Return type:

dict[str, Any]

model_dump(**kwargs)[source]

Alias for to_dict for Pydantic compatibility.

Parameters:

**kwargs (Any) – Arguments to pass to model_dump

Returns:

Dictionary representation

Return type:

dict[str, Any]

save(update_fields=None)[source]

Save this instance to the API.

Creates or updates based on whether the object has an ID.

Parameters:

update_fields (list[str] | None) – List of fields to update (None = all fields)

Raises:

APIException – If client is not set

Example

>>> policy = Policy(policy_number='POL-001', premium_amount=1500)
>>> policy.save()  # Creates new
>>> policy.premium_amount = 2000
>>> policy.save(update_fields=['premium_amount'])  # Updates
delete()[source]

Delete this instance from the API.

Raises:

APIException – If client is not set or object has no ID

Example

>>> policy = Policy.objects.get(id=123)
>>> policy.delete()
refresh_from_api()[source]

Refresh this instance’s data from the API.

Raises:

APIException – If client is not set or object has no ID

Example

>>> policy = Policy.objects.get(id=123)
>>> # ... time passes, data may have changed ...
>>> policy.refresh_from_api()  # Reload from API
__repr__()[source]

String representation.

__str__()[source]

Human-readable string.

Model Registration

django_api_orm.register_models(client, *model_classes)[source]

Register model classes with a sync client.

This assigns a Manager instance to each model’s ‘objects’ attribute.

Parameters:

Example

>>> client = ServiceClient(base_url="https://api.example.com")
>>> register_models(client, Policy, Claim, Broker)
>>> policies = Policy.objects.filter(status='active')

Example Usage

from pydantic import BaseModel
from django_api_orm import APIModel, ServiceClient, register_models

class UserSchema(BaseModel):
    id: int | None = None
    name: str
    email: str

class User(APIModel):
    _schema_class = UserSchema
    _endpoint = "/api/v1/users/"

with ServiceClient(base_url="https://api.example.com") as client:
    register_models(client, User)

    # Create instance
    user = User.objects.create(name="Alice", email="alice@example.com")

    # Save instance
    user.name = "Alice Updated"
    user.save()

    # Delete instance
    user.delete()

Asynchronous Models

class django_api_orm.async_base.AsyncAPIModel(**kwargs)[source]

Bases: object

Base class for async API models.

Provides Django ORM-like interface for working with API resources asynchronously. Must be subclassed with _schema_class and _endpoint defined.

Example

>>> class PolicySchema(BaseModel):
...     id: int | None = None
...     policy_number: str
...     premium_amount: float
>>>
>>> class Policy(AsyncAPIModel):
...     _schema_class = PolicySchema
...     _endpoint = "/api/v1/policies/"
>>>
>>> # Register with async client
>>> Policy.objects = AsyncManager(Policy, async_client)
objects: AsyncManager[AsyncAPIModel]
__init__(**kwargs)[source]

Initialize model instance.

Parameters:

**kwargs (Any) – Field values or _pydantic_instance

__setattr__(name, value)[source]

Set attribute and update internal pydantic instance.

Parameters:
  • name (str) – Attribute name

  • value (Any) – Attribute value

classmethod get_endpoint()[source]

Get the API endpoint for this model.

Returns:

API endpoint path

Return type:

str

classmethod get_schema_class()[source]

Get the Pydantic schema class for this model.

Returns:

Pydantic BaseModel class

Return type:

type[BaseModel]

classmethod from_api(data, client=None)[source]

Create model instance from API response data.

Parameters:
Returns:

Model instance

Return type:

AsyncAPIModel

to_dict(exclude_unset=False, exclude_none=False)[source]

Convert model to dictionary.

Parameters:
  • exclude_unset (bool) – Exclude fields that weren’t explicitly set

  • exclude_none (bool) – Exclude fields with None values

Returns:

Dictionary representation

Return type:

dict[str, Any]

model_dump(**kwargs)[source]

Alias for to_dict for Pydantic compatibility.

Parameters:

**kwargs (Any) – Arguments to pass to model_dump

Returns:

Dictionary representation

Return type:

dict[str, Any]

async save(update_fields=None)[source]

Save this instance to the API (async).

Creates or updates based on whether the object has an ID.

Parameters:

update_fields (list[str] | None) – List of fields to update (None = all fields)

Raises:

APIException – If client is not set

Example

>>> policy = Policy(policy_number='POL-001', premium_amount=1500)
>>> await policy.save()  # Creates new
>>> policy.premium_amount = 2000
>>> await policy.save(update_fields=['premium_amount'])  # Updates
async delete()[source]

Delete this instance from the API (async).

Raises:

APIException – If client is not set or object has no ID

Example

>>> policy = await Policy.objects.get(id=123)
>>> await policy.delete()
async refresh_from_api()[source]

Refresh this instance’s data from the API (async).

Raises:

APIException – If client is not set or object has no ID

Example

>>> policy = await Policy.objects.get(id=123)
>>> # ... time passes, data may have changed ...
>>> await policy.refresh_from_api()  # Reload from API
__repr__()[source]

String representation.

__str__()[source]

Human-readable string.

Model Registration

django_api_orm.register_async_models(client, *model_classes)[source]

Register model classes with an async client.

This assigns an AsyncManager instance to each model’s ‘objects’ attribute.

Parameters:

Example

>>> async_client = AsyncServiceClient(base_url="https://api.example.com")
>>> register_async_models(async_client, Policy, Claim, Broker)
>>> policy = await Policy.objects.get(id=123)

Example Usage

from django_api_orm import AsyncAPIModel, AsyncServiceClient, register_async_models

class User(AsyncAPIModel):
    _schema_class = UserSchema
    _endpoint = "/api/v1/users/"

async with AsyncServiceClient(base_url="https://api.example.com") as client:
    register_async_models(client, User)

    # Create instance
    user = await User.objects.create(name="Alice", email="alice@example.com")

    # Save instance
    user.name = "Alice Updated"
    await user.save()

    # Delete instance
    await user.delete()

See Also