Entity¶
- class nextorm.entity.Entity[source]¶
Bases:
objectBase class for all NextORM entities.
Define fields using type aliases:
class Product(Entity): name: Req[str] price: Req[float] description: Opt[str]
Fields are discovered automatically; no
db.Entitycoupling needed.- after_load()[source]¶
Called after an existing entity is loaded from the database.
- Return type:
None
- before_insert()[source]¶
Called before a new entity is saved to the database for the first time.
- Return type:
None
- after_insert()[source]¶
Called after a new entity is saved to the database for the first time.
- Return type:
None
- before_update()[source]¶
Called before a modified entity is saved to the database.
- Return type:
None
- get_pk()[source]¶
Return the primary key value of this entity instance.
Returns
Nonewhen the entity has no primary key field or when the PK has not been set yet (e.g. before the firstdb.save()call).Example:
u = User(name="alice") db.save(u) pk = u.get_pk() # → 1
- Return type:
- set(**kwargs)[source]¶
Bulk-assign attribute values in a single call.
Equivalent to calling
setattr(self, k, v)for every provided keyword argument. Dirty-tracking in the active session is updated automatically because each assignment goes through the descriptor:user.set(name="bob", age=30)
- Parameters:
kwargs (Any)
- Return type:
None
- delete()[source]¶
Delete this entity from the database using its attached database context.
The entity must have been loaded or saved via a
Database(orAsyncDatabase) so that the_db_context attribute is available. Usedelete_instance()directly if you want to pass the database explicitly.Raises
RuntimeErrorwhen the entity has no attached database context.- Return type:
None
- classmethod get(**kwargs)[source]¶
Return the first entity matching all given field values, or
None.Raises
RuntimeErrorif more than one row matches. Uses_find_db_for_entity()to locate the mapped database.Example:
user = User.get(name="alice")
- classmethod exists(**kwargs)[source]¶
Return
Trueif at least one entity matches all given field values.Uses
_find_db_for_entity()to locate the mapped database.Example:
if User.exists(name="alice"): ...
- classmethod select()[source]¶
Return a
QuerySetfor this entity.Convenience shortcut for
db.select(Entity)that locates the mapped database automatically.Example:
active_users = User.select().filter(User.active == True).fetch_all() count = User.select().count()
- Return type:
- classmethod aselect()[source]¶
Return an
AsyncQuerySetfor this entity.Sync builder — returns an
AsyncQuerySetdirectly (noawaitneeded). Async counterpart ofselect(). Locates the mappedAsyncDatabaseautomatically.Example:
users = await User.aselect().filter(User.active == True).fetch_all()
- Return type:
- async classmethod aget(**kwargs)[source]¶
Return the first entity matching all given field values, or
None.Async counterpart of
get(). RaisesRuntimeErrorif more than one row matches.Example:
user = await User.aget(email="alice@example.com")
- to_dict(only=None, exclude=None, *, with_collections=False, with_lazy=False, related_objects=False)[source]¶
Serialize this entity to a plain Python dictionary.
Parameters¶
- only:
If given, only the listed field names are included. Relations are included only when with_collections or related_objects is also
True.- exclude:
Field names to exclude. Applied after only.
- with_collections:
When
True,Set[T]relation attributes are included as lists of theirto_dict()results. Requires the collections to have been prefetched or lazily loaded beforehand.- with_lazy:
When
False(the default) lazy fields that have not yet been loaded are omitted from the result. PassTrueto include them; unloaded lazy fields are fetched on demand (sync databases only).- related_objects:
When
True, loadedSingle[T]relation attributes are included as nestedto_dict()results. If the related object has not been loaded, the raw FK value ({name}_id) is included instead.
Example:
user.to_dict() # → {"id": 1, "name": "alice", "age": 30} user.to_dict(exclude=["id"]) # → {"name": "alice", "age": 30} user.to_dict(with_collections=True) # → {"id": 1, ..., "posts": [{"id": 5, "title": "hi", ...}]} article.to_dict(with_lazy=True) # → {"id": 1, "title": "hi", "body": "<full text>"} comment.to_dict(related_objects=True) # → {"id": 1, "text": "great", "author": {"id": 2, "name": "bob"}}
- classmethod select_by_sql(db, sql, params=None)[source]¶
Execute sql and return all rows mapped to instances of this entity.
Convenience wrapper around
db.select(cls).raw(sql, params).Example:
users = User.select_by_sql(db, "SELECT * FROM user WHERE age > ?", [18])
- classmethod get_by_sql(db, sql, params=None)[source]¶
Execute sql and return the first row as an entity instance, or
None.Convenience wrapper around
db.select(cls).raw_one(sql, params).Example:
user = User.get_by_sql(db, "SELECT * FROM user WHERE id = ?", [1])
- async classmethod aselect_by_sql(db, sql, params=None)[source]¶
Async equivalent of
select_by_sql().Example:
users = await User.aselect_by_sql(db, "SELECT * FROM user WHERE age > %s", [18])
- Parameters:
db (AsyncDatabase)
sql (str)
params (list[Any] | None)
- Return type:
list[Self]
- async classmethod aget_by_sql(db, sql, params=None)[source]¶
Async equivalent of
get_by_sql().Example:
user = await User.aget_by_sql(db, "SELECT * FROM user WHERE id = %s", [1])
- Parameters:
db (AsyncDatabase)
sql (str)
params (list[Any] | None)
- Return type:
Self | None
- class nextorm.entity.EntityMeta[source]¶
Bases:
typeMetaclass that processes
Annotatedfield specs at class definition time.
- class nextorm.entity.FieldInfo[source]¶
Bases:
objectResolved information about a single persistent field.
- name¶
- py_type¶
- spec¶
- class nextorm.entity.RelationInfo[source]¶
Bases:
objectResolved information about a relation field.
- __init__(name, spec)[source]¶
- Parameters:
name (str)
spec (RelationSpec)
- Return type:
None
- name¶
- spec¶
- class nextorm.collection.RelatedCollection[source]¶
Bases:
GenericA lazy, database-backed collection representing one side of a relation.
Instances are created by
SetDescriptoron first attribute access. They hold a weak logical reference to the owner entity so that individual collections can be GC’d when not needed.The collection is not thread-safe. Use separate collection objects in separate threads.
Parameters¶
- owner:
The entity instance that owns this relation attribute.
- ri:
The
RelationInfofor this relation.- db:
The
Databaseto query.Nonewhen the owner entity was not loaded from a database (e.g. a freshly created but unsaved entity).
- __init__(owner, ri, db)[source]¶
- Parameters:
owner (Entity)
ri (RelationInfo)
db (Database | None)
- Return type:
None
- filter(*conditions)[source]¶
Return a filtered
QuerySetfor this collection.- Parameters:
conditions (Any)
- Return type:
QuerySet[T]
- order_by(*items)[source]¶
Return an ordered
QuerySetfor this collection.- Parameters:
items (Any)
- Return type:
QuerySet[T]
- page(pagenum, pagesize=10)[source]¶
Return a page of this collection’s items (1-based page numbers).
- add(*items)[source]¶
Add one or more items to this collection.
For M2M: inserts rows into the join table. For O2M: updates the FK column on each item.
- Parameters:
items (T)
- Return type:
None