Model
A model in Dataloom is a top-level class that facilitates the creation of complex SQL tables using regular Python classes. This example demonstrates how to define two tables, User and Post, by creating classes that inherit from the Model class.
from dataloom import (
Loom,
Model,
PrimaryKeyColumn,
Column,
CreatedAtColumn,
UpdatedAtColumn,
TableColumn,
ForeignKeyColumn,
)
class User(Model):
__tablename__:TableColumn = TableColumn(name="users")
id = PrimaryKeyColumn(type="int", auto_increment=True)
name = Column(type="text", nullable=False, default="Bob")
username = Column(type="varchar", unique=True, length=255)
# timestamps
createdAt = CreatedAtColumn()
updatedAt = UpdatedAtColumn()
class Post(Model):
__tablename__: TableColumn = TableColumn(name="posts")
id = PrimaryKeyColumn(type="int", auto_increment=True, nullable=False, unique=True)
completed = Column(type="boolean", default=False)
title = Column(
type="varchar",
length=255,
nullable=False,
)
# timestamps
createdAt = CreatedAtColumn()
updatedAt = UpdatedAtColumn()
# relations
userId = ForeignKeyColumn(
User, type="int", required=True, onDelete="CASCADE", onUpdate="CASCADE"
)
Within the
Usermodel definition, the table name is explicitly specified using the__tablename__property, set to"users". This informsdataloomto use the provided name instead of automatically deriving it from the class name. IfTableColumnis not specified, the class name becomes the default table name during the synchronization of tables. To achieve this, theTableColumnclass is used, accepting the specified table name as an argument.
Note
When defining a table name, it’s not necessary to specify the property as __tablename__. However, it’s considered good practice to name your table column like that to avoid potential clashes with other columns in the table.
Every table must include exactly one primary key column unless it is a
joint_tableforN-Nrelations that requires no primary key column. To define this, thePrimaryKeyColumnclass is employed, signaling todataloomthat the specified field is a primary key.The
Columnclass represents a regular column, allowing the inclusion of various options such as type and whether it is required.The
CreatedAtColumnandUpdatedAtcolumn types are automatically generated by the database as timestamps. If timestamps are unnecessary or only one of them is needed, they can be omitted.The
ForeignKeyColumnestablishes a relationship between the current (child) table and a referenced (parent) table.