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 User model definition, the table name is explicitly specified using the __tablename__ property, set to "users". This informs dataloom to use the provided name instead of automatically deriving it from the class name. If TableColumn is not specified, the class name becomes the default table name during the synchronization of tables. To achieve this, the TableColumn class 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_table for N-N relations that requires no primary key column. To define this, the PrimaryKeyColumn class is employed, signaling to dataloom that the specified field is a primary key.

  • The Column class represents a regular column, allowing the inclusion of various options such as type and whether it is required.

  • The CreatedAtColumn and UpdatedAt column 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 ForeignKeyColumn establishes a relationship between the current (child) table and a referenced (parent) table.