F
FasORM
v0.1.0

Models & Field Types

FasORM models inherit from Model and use declarative field types. Learn how to define models, leverage field attributes, perform Active Record CRUD operations, and serialize records.

Defining a Model

Models are subclassed from fasorm.Model. By default, FasORM automatically computes the pluralized table name (e.g. Userusers) and includes an id primary key along with created_at and updated_at timestamps.

app/models/product.py
from fasorm import Model, String, Decimal, Integer, Boolean, Jsonb

class Product(Model):
    name = String(150)
    sku = String(50, unique=True)
    price = Decimal(precision=10, scale=2)
    stock = Integer(default=0)
    is_published = Boolean(default=True)
    metadata = Jsonb(nullable=True)

Complete Field Type Reference

FasORM supports over 30 expressive field types:

Field Class SQL Type Equivalent Options / Description
String(length=255) VARCHAR(length) Variable-length string. Default length is 255.
Char(length=10) CHAR(length) Fixed-length string.
Text(), TinyText(), MediumText(), LongText() TEXT Unlimited / medium / long block text.
Integer(), BigInteger(), SmallInteger(), TinyInteger(), MediumInteger() INTEGER / BIGINT / SMALLINT Signed integer fields.
UnsignedInteger(), UnsignedBigInteger(), UnsignedSmallInteger(), UnsignedTinyInteger() INTEGER (Check >= 0) Unsigned integers (non-negative).
Float(), Decimal(precision, scale) FLOAT / NUMERIC Floating point or exact fixed-point decimal.
Boolean() BOOLEAN Boolean true/false. Supports default=True.
Date(), Time(), TimeTz() DATE / TIME Date and time fields (with timezone option).
DateTime(), DateTimeTz(), Timestamp(), TimestampTz() DATETIME / TIMESTAMP Date-time timestamp fields.
Year() INTEGER 4-digit year representation.
Json(), Jsonb() JSON / JSONB Structured JSON documents (Postgres JSONB / SQLite JSON).
Uuid(), Ulid() UUID / VARCHAR(26) Universally unique identifiers.
IpAddress(), MacAddress() VARCHAR(45) / VARCHAR(17) IPv4/v6 and MAC address fields.
Enum(options=[...]), Set(options=[...]) ENUM Restricted choices enum or set.
Vector(dim=1536) VECTOR(dim) pgvector embedding vector field for AI applications.
Binary() BLOB / BYTEA Raw binary byte storage.

Active Record CRUD Operations

Interact directly with models using async class and instance methods:

Create Record

Python
user = await User.create(name="Sandy", email="[email protected]")
print(user.id)  # Populated auto-increment ID

Find by Primary Key

Python
user = await User.find(1)
user_or_fail = await User.find_or_fail(99)  # Raises ModelNotFoundError if missing

First or Create & Update or Create

Python
# Find user by email or create new one
user = await User.first_or_create(
    search={"email": "[email protected]"},
    defaults={"name": "Alice"}
)

# Update matching record or create
user = await User.update_or_create(
    search={"email": "[email protected]"},
    defaults={"name": "Alice Updated"}
)

Instance Update, Save & Delete

Python
# Update specific fields
await user.update(name="New Name")

# Modify and save
user.name = "Another Name"
await user.save()

# Delete record
await user.delete()

# Bulk Destroy by IDs
deleted_count = await User.destroy(1, 2, 3)

Record Serialization

Convert models to standard Python dictionaries or JSON strings. Eager-loaded relations are automatically included!

Python
user = await User.with_("posts").find(1)

# Dictionary serialization
data = user.to_dict()
# -> {"id": 1, "name": "Sandy", "posts": [{"id": 10, "title": "First Post"}]}

# Disable eager relationship serialization
data_flat = user.to_dict(include_relations=False)

# JSON string serialization
json_str = user.to_json()