Features
Define one-to-one relationships between feature sets.
In a one-to-one relationship, two feature sets have at most one
feature set on both sides of the relation.
One-to-one relationships are specified via the function
has_one
, where the first argument specifies a function returning
how to join the tables.
In the example below, users have an associated profile:
from chalk.features import has_one, ...
@features
class Profile:
...
user_id: str
email_age_years: float
@features
class User:
...
uid: str
profile: Profile = has_one(lambda: Profile.user_id == User.uid)
The `lambda` solves forward references, letting you reference `User` before it is defined.
Now, you can reference features on Profile
through User
. For example:
user_email_age = User.profile.email_age_years
You can also add the back-reference to User
from Profile
.
You don’t have to explicitly use has_one
again on Profile
, however.
Instead, the join condition is assumed to be symmetric and copied over.
Building on the above example, all you need to do
to complete the one-to-one relationship is to add a User
to
the Profile
class:
@features
class Profile:
...
user_id: str
email_age_years: float
user: "User"
@features
class User:
...
uid: str
profile: Profile = has_one(lambda: Profile.user_id == User.uid)
Here you need to use quotes around `User` to use a forward reference.
You can define optional relationships simply by
using the typing.Optional[...]
keyword:
from typing import Optional
@features
class User:
...
uid: str
profile: Profile = has_one(lambda: Profile.user_id == User.uid)
profile: Optional[Profile] = has_one(lambda: Profile.user_id == User.uid)