FKey¶
A FKey attribute represents a foreign key (or reverse foreign key) on a
relation. halfORM exposes all FKs automatically; give them friendly names
via the Fkeys class attribute and use them to navigate between tables or
compose JOIN conditions.
Two usage patterns:
- Call the attribute —
post.author_fk()— to navigate: returns the related relation restricted to rows linked to the current predicate. .set(...)— adds a JOIN condition on the owning relation. Three forms, all without importing the related class:.set()— join all rows (tautological predicate)..set(field=value, ...)— join with constraints..set(rel)— join against an existingRelationinstance.
Print any relation instance to discover FK names (internal names to copy
into Fkeys).
See Learn halfORM in half an hour for a full walkthrough.
Navigation¶
__call__(__cast__=None, **kwargs)
¶
Navigate to the related relation, restricted to linked rows.
Returns a new predicate on the related table whose extension is
limited to rows that are linked to the current predicate's
extension via this foreign key. Additional kwargs are passed
as extra constraints on the returned relation.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
**kwargs
|
optional constraints forwarded to the related relation's constructor. |
{}
|
Returns:
| Name | Type | Description |
|---|---|---|
Relation |
a new predicate on the related table. |
Join condition¶
set(ho_to_rel=None, **kwargs)
¶
Bind this foreign key to a relation, adding a JOIN condition.
After calling .set(...), queries on the owning relation
automatically include a JOIN against the related table filtered by
the given constraints.
Three calling forms — no import of the related class required:
.set()— joins all rows (tautological predicate)..set(field=value, ...)— joins with constraints, instantiating the related class internally..set(rel)— joins against an already-built :class:~half_orm.relation.Relationinstance.
Parameters:
| Name | Type | Description | Default |
|---|---|---|---|
ho_to_rel
|
Relation | None
|
an existing relation to join against.
Mutually exclusive with |
None
|
**kwargs
|
field constraints forwarded to the related class
constructor. Ignored when |
{}
|
Returns:
| Type | Description |
|---|---|
|
self — for chaining. |
Raises:
| Type | Description |
|---|---|
RuntimeError
|
if |
RuntimeError
|
if |
RuntimeError
|
if setting this FK would create a cycle in the join graph. |
Example
Without importing the related class:
post = Post()
post.author_fk.set() # all authors
post.author_fk.set(last_name=('like', 'Mar%')) # filtered
With an existing relation:
New in version 0.18.6: raises RuntimeError if setting this FK would create a cycle in the join graph.