Relationships
Database tables are often related to one another. FasORM supports declarative relationships: One to One, One to Many, and Many to Many.
Relationship Descriptors
| Descriptor | Relationship Type | Example Declaration |
|---|---|---|
HasMany("Target") |
One to Many (Parent) | posts = HasMany("Post") |
BelongsTo("Target") |
Inverse One to Many (Child) | user = BelongsTo("User") (Auto creates user_id FK) |
HasOne("Target") |
One to One (Parent) | profile = HasOne("Profile") |
BelongsToMany("Target", pivot="...") |
Many to Many | roles = BelongsToMany("Role", pivot="user_roles") |
One to Many Example (User & Post)
models.py
from fasorm import Model, String, Text, HasMany, BelongsTo
class User(Model):
name = String()
email = String(unique=True)
posts = HasMany("Post")
class Post(Model):
title = String()
body = Text()
user = BelongsTo("User") # Automatically creates user_id FK column
Querying One to Many Relationships
Python
# Eager-load posts with user
users = await User.with_("posts").get()
for post in users[0].posts:
print(post.title)
# Inverse BelongsTo loading
post = await Post.with_("user").find(1)
print(post.user.name)
One to One Example (User & Profile)
models.py
class User(Model):
name = String()
profile = HasOne("Profile")
class Profile(Model):
bio = Text()
avatar_url = String()
user = BelongsTo("User")
Many to Many Example (User & Role)
models.py
class User(Model):
name = String()
roles = BelongsToMany("Role", pivot="user_roles")
class Role(Model):
name = String(unique=True)
users = BelongsToMany("User", pivot="user_roles")
Pivot Table Creation
When defining
BelongsToMany, create the pivot table (e.g. user_roles) in a migration with foreign keys pointing to both user_id and role_id.