Skip to content

Field Types

Fullfinity provides a rich set of field types for modeling your data.

Fields are generic typing descriptors, so editors and pyright resolve record.<field> to its real Python type instead of Any — both inside the model’s own methods (self.name) and on references elsewhere:

class Product(Model):
name = Char(max_length=255) # record.name → str
price = Float() # record.price → float
active = Boolean() # record.active → bool
async def label(self) -> str:
return self.name.upper() # type-checked: self.name is str

Scalar fields map to their obvious types (Char/Text/Selection → str, Integer → int, Float/Monetary → float, Boolean → bool, Date → date, Datetime → datetime, Binary → bytes); JSON/File and relational fields (ManyToOne, OneToMany, …) resolve to Any (relations are awaited/lazy). This is typing-only — at runtime the record serves its own values, so the descriptors add no behavior. Class-level access (Product.name) still returns the Field instance for introspection.

Run the checker with the project’s pyrightconfig.json.

All fields support these options:

OptionTypeDefaultDescription
requiredboolFalseNOT NULL constraint
defaultanyNoneDefault value (can be callable)
descriptionstrNoneHuman-readable label — the field’s caption on forms/lists AND the name used in any error message about the field (see Exceptions). Keep it a short caption; put explanation in hint. Omitted, the framework falls back to a readable form of the field name (due_date → “Due Date”) — never the raw identifier
hintstrNoneHelp text, shown as an ⓘ tooltip beside the field’s label on forms — no view change needed (a hint: in the view’s properties overrides it, exactly as a view label: overrides description)
readonlyboolderived → True, else FalseField cannot be edited. Defaults to True for a derived value — a related_field, or a calculate with no setter — since the record doesn’t own the value. Pass it explicitly to override in either direction (see Calculated fields are readonly by default)
indexboolFalseCreate database index. Redundant with unique=True, whose constraint is already an index — no second one is created
uniqueboolFalseEnforce uniqueness at database level. The constraint indexes the column, so lookups by it are indexed without index=True
cloneboolTrue (False for OneToMany/OneToOne)Include field value when duplicating a record — see Duplicating records
storeboolTrueStore in database
calculatestrNoneCalculate method name
setterstrNoneMethod to call when setting a calculated field value
calculate_elevatedboolFalseBypass access rights during calculation
sql_predicatestrNoneMakes a non-stored calculated Boolean filterable — see Filtering a non-stored Boolean
company_scopedboolFalseStore a separate value per company (see Company-Scoped Fields)
groupslist[str][]Gate read/write of this field by group at the API boundary (see below)
validatorslist[]List of validation functions (see Validators)
prefix_fieldstrNoneDynamic field path for prefix display (e.g., "currency__symbol")
suffix_fieldstrNoneDynamic field path for suffix display (e.g., "uom__name")

Filtering a non-stored Boolean (sql_predicate)

Section titled “Filtering a non-stored Boolean (sql_predicate)”

A calculated field with store=False has no column, so Q(my_flag=True) has nothing to compare. When the value genuinely can’t be stored — it depends on who is asking, or on another table that changes without touching this record — name a method that answers in SQL instead:

class Ticket(Model):
awaiting_me = Boolean(
calculate="_calc_awaiting_me", store=False,
description="Awaiting Me", sql_predicate="_awaiting_me_sql",
)
@Model.calculate()
async def _calc_awaiting_me(self):
uid = env_ctx.get().user_id
for record in self:
record.awaiting_me = record.reviewer_id == uid and record.state == "Review"
def _awaiting_me_sql(cls, alias):
# The condition for the rows where the value is TRUE. `%s` marks each bound parameter.
return f"({alias}.reviewer_id = %s AND {alias}.state = 'Review')", [env_ctx.get().user_id]
  • The method receives the table alias of the row being filtered and returns (sql, params) for the rows where the value is true; Q(field=False) is that condition negated. The keyword form — Model.filter(field=True) — and a search-view filter expression both work the same way.
  • Only =True / =False can be asked — any other lookup raises.
  • The compute and the predicate state the same rule twice (once per row, once per table). Write a test that they agree on a mixed set of records.
  • sql_predicate on a stored field raises: a stored field already has a column to filter on. If the value can be stored, store it.

groups restricts who can read or write a single field to members of the listed groups:

cost_price = Float(groups=["inventory_manager_group"]) # only managers see/edit it
  • Read — the serializer omits the field from API output for users not in any listed group. They never see the value (the column/data is untouched).
  • Write — the create/update endpoints raise AccessError if such a user tries to set the field.
  • Admin bypass — members of core_admin always have access.
  • Boundary-only — this is enforced at the API serializer and create/update endpoints, not in-process. Direct ORM access inside server code is intentionally ungated, so your own model logic can always read/write the field.

Single-line text with max length:

name = Char(max_length=255, required=True)
email = Char(max_length=200, index=True)
sku = Char(max_length=50, description="Stock Keeping Unit")
# With validation
code = Char(max_length=10, regex=r"^[A-Z]{2}-\d{4}$")
# A telephone number
phone = Char(max_length=64, phone=True, description="Phone")
# A web address a person follows
website = Char(url=True, description="Website")
PropertyTypeDescription
max_lengthintMaximum character length (required)
min_lengthintMinimum character length
regexstrRegular expression pattern for validation
phoneboolThe field holds a telephone number, stored in E.164 form (see below)
urlboolThe field holds a web address a person follows: drawn as a link, stored with its scheme (see below)

A phone number is compared — an SMS opt-out against a campaign’s recipients, an inbound reply’s sender against the address book — so it is stored in one form: E.164 (+14155550112), with ;ext=23 appended when the number has an extension. Declare every field that holds a telephone number with phone=True; a plain Char stores whatever was typed, and "+1 (415) 555-0112" and "+14155550112" then never match.

  • Writing. A number with its country code (+… or 00…) is stored in E.164. A number without one (0412 345 678) is read in the current company’s country (env.company_id, or the company inside as_company(...)). Nothing is refused: text that does not read as a dialable number — a local number with no area code, a note like “ask for Sam”, a national number when the company has no country — is stored exactly as typed, so a website lead or a checkout address is never lost over its phone number. Only those values miss the comparison.
  • Filtering. Filter values are converted the same way, so Contact.filter(phone="+1 (415) 555-0112") finds the contact stored as +14155550112, in a keyword filter, a Q(...) and an __in list alike. A search fragment that is not a whole number (phone__icontains="5550") is passed through untouched.
  • Comparing in Python. Compare against the stored value, or canonicalise a number you received first with fullfinity.engine.phone.canonical_international(value).
  • Existing data. Turning phone=True on for a field that already holds rows needs a data ledger entry in your module whose hook calls await fullfinity.engine.phone.normalize_stored_numbers(env). It rewrites every installed phone=True column (idempotently), reading a national number in its row’s company country, and leaves a value that is not a dialable number as it was typed.

A website, a meeting’s join link or a tracking link is something a person clicks. Declare it with url=True and every screen draws it as one, without the view naming a widget:

  • Read-only (lists, kanban cards, a locked form): a link that opens in a new tab, with a copy button.
  • Editing: the ordinary text box with an open icon at its edge, which opens what is typed in the box at that moment.
  • Writing. An address typed as a bare host (acme.com, www.acme.co.uk/about) is stored with https://, so the link opens. Nothing is refused. Text that does not read as an address is stored as typed, and a search for acme is never rewritten.
  • Not every URL field. Endpoints a developer pastes in (webhooks, OAuth token URLs, map tile servers) are not followed by anyone, so they stay plain Chars.
  • Existing data. Turning url=True on for a field that already holds rows needs a data ledger entry whose hook calls await fullfinity.engine.fields.normalize_stored_urls(env). It gives every installed url=True column its scheme, and it is idempotent.

A view that writes widget: Url on such a field is repeating the default, and ./fullfinity-server check --only views reports it.

Unlimited multi-line text:

description = Text()
notes = Text(description="Internal Notes")

Inlined images are extracted on create. A Char or Text value that arrives holding an image as a data: URI — which is what a rich-text editor produces when the record it is editing has no id yet, and so nothing to attach a file to — has those images written to the filestore as Attachment rows against the new record, and the src rewritten to the attachment’s URL. It happens once, at the end of create, because that is the first moment an attachment can reference the record at all.

The attachments it creates are marked inline, which keeps them out of the record’s Files panel — an image already visible in the text is not a document filed against the record.

You do not opt in and there is nothing to configure. A value with no data: image is left byte-for-byte alone, and an image whose payload will not decode is left inline rather than stored, so a truncated paste loses its picture instead of failing the create. Updates are not scanned: once a record has an id the editor uploads directly, so an update can only carry a data: URI that this pass already rewrote.

A Char or Text field holding content a customer reads — a product name, a category, page copy — can carry a value per language:

name = Char(max_length=255, description="Product Name", translate=True)

The source value stays in its own column and a per-language overlay is stored beside it, so reads show the reader’s language and lookups, uniqueness and integrations keep resolving against the source. Opt-in per field, because name and barcode are the same type. See Translatable Values.

searchable=True puts a field in the model’s search set: what a term typed into the list’s search box, a relation picker, or Model.search_q(text) is matched against.

email = Char(max_length=255, description="Email", searchable=True)
content = Text(description="Message Content", searchable=True)

The set is:

  • The name field (_name_field), always — no declaration needed. When the name is itself a relation (a line named by its product), the related record’s name.

  • Every Char/Text field declared searchable=True.

  • Every relation declared searchable. On a ManyToOne, OneToOne, OneToMany or ManyToMany, searchable=True matches the related record’s name; a list names paths inside the related model:

    customer = ManyToOne("Contact", related_name="orders", on_delete="RESTRICT", searchable=True)
    variants = OneToMany("ProductVariant", related_name="product", searchable=["default_code", "barcode"])
    lines = OneToMany("PlanLine", related_name="plan", searchable=["equipment"]) # a line's equipment's name

    A path may cross further relations, and must end at the related model’s name or at a field declared searchable=True there — a path that does not raises ConfigurationError naming it.

What a term matches. Every word typed must appear in some field of the set, ignoring case and markup — different words may match different fields, so “acme london” finds the contact named Acme whose city is London (if city is searchable).

  • A word of three or more characters may appear anywhere: “4602” finds a phone number containing it, “phone” finds “iPhone”, “0042” finds SO20260042.
  • A two-character word must start a word (“jo” finds John, not Major).
  • A one-character word in the search box matches only a whole one-character word — as a prefix it would match a large share of any table. Relation pickers check every word against the record’s name together, so there a trailing letter narrows the list as you type (“orla s” offers Orla Smith).
  • Accents must match: “muller” does not find “Müller”.

Who can find what. A field the reader may not query — group-restricted, a secret, or on a model they cannot read — is left out of their search set, so a value they cannot see cannot be found by typing it. A searchable relation matches only related records the reader may read.

Translated fields (translate=True) are matched in the reader’s language as well as the source.

The indexes. Every field in the set keeps two: a trigram index (from PostgreSQL’s bundled pg_trgm extension, enabled automatically) for words matched anywhere, and an index over its words for short words and for the __search lookup. Both are created on install or upgrade and dropped again when the field stops being searched — there is no second column to keep in step and nothing to backfill. That is what keeps search fast as a table grows: on a million contacts, a search across name, email, phone and tax ID returns a page with its total count in tens of milliseconds. The cost is on writes — each searchable field adds an index every insert and update maintains — so declare the fields people actually type, not every text field.

Not accepted on an Encrypted field (ciphertext has no words) or on one with no column of its own (store=False, company_scoped=True) — both raise when the model is defined.

A credential field that is encrypted at rest. The value is plaintext in Python but stored as Fernet ciphertext in the column (keyed off the configured SECRET_KEY). Use it for API keys, OAuth tokens, and other secrets.

api_secret = Encrypted(description="API Secret")
access_token = Encrypted(description="Access Token")
  • Reads/writes are transparent — assign and read the field as a normal string; the value is encrypted on the way to the database and decrypted on the way back.
  • Backed by VARCHAR (sized for ciphertext via max_length, default 2048), so converting an existing Char secret to Encrypted keeps its column (a widening at most).
  • Converting a Char to Encrypted still needs its stored values encrypted. The type change alters how a value is written, not what the column already holds: every value saved before it stays plain text — readable in the database and in every backup — and is read back unchanged (values without the enc:v1: prefix are returned as they are). So the schema gate treats the conversion as a change to record, and resolve records an encrypt ledger entry for it without asking; -u all then encrypts every stored plain-text value. See Migrations & Upgrades.
  • The value never leaves the server. An API response — a form, a list, an export — carries •••••••• where a value is stored and null where none is, for every user including administrators, so a settings form still shows that a key is configured. Sending •••••••• back (a form saved without touching the field) keeps the stored value; any other value replaces it, and an empty one clears it. Your own Python code reads the plaintext as usual.
  • A client filter, sort or group-by naming the field is refused. Server code that needs to ask whether a key is configured filters in Python as usual.
  • Every credential an integration stores must be Encrypted — a plain Char is sent in full to every role that can read the record. Values that are public by design (a publishable key the browser uses to start a checkout) stay Char.

:::caution Key rotation makes existing values unreadable The Fernet key is derived deterministically from SECRET_KEY. Rotating SECRET_KEY makes all previously-stored ciphertext undecryptable. On a decrypt failure the field does not raise — it returns the stored token unchanged (the prefix-stripped ciphertext), so reads never crash and no data is lost, but the plaintext is gone until you restore the original key. If SECRET_KEY is unset or a placeholder, the server refuses to start, and reading/writing an Encrypted field raises ConfigurationError. Plan a re-encryption step if you ever rotate the key. :::

Whole numbers:

quantity = Integer(default=1)
sequence = Integer(default=10)
age = Integer(required=True, min_value=0, max_value=150)
PropertyTypeDescription
min_valueintMinimum allowed value
max_valueintMaximum allowed value

Integer stores as a 32-bit column, so it holds values up to about 2.1 billion — the right choice for quantities, counts, sequences, ages, years, and the like.

A 64-bit whole number, for the rare scalar that can exceed Integer’s ~2.1 billion range — a byte count, an externally-assigned identifier, an epoch-nanosecond timestamp, a bitmask:

file_size_bytes = BigInt(default=0)
external_ref = BigInt(min_value=0)

BigInt behaves exactly like Integer in Python (same validation, same min_value/max_value, arbitrary-precision int values); only the stored column width differs. You do not need BigInt for record ids or relations — a model’s own id and every ManyToOne/OneToOne foreign key are already 64-bit, so they never run out of ids. Reach for BigInt only when a declared scalar field genuinely needs the extra range.

Floating-point numbers with configurable precision:

# Static precision (2 decimal places)
weight = Float(precision=2, default=0.0)
percentage = Float(precision=4, min_value=0, max_value=100)
# Dynamic precision from field on same model
rate = Float(precision="decimal_places")
# Dynamic precision from related model (one level only)
quantity = Float(precision="uom__rounding")
# Blank is a value of its own: unset stays None instead of reading as 0.0
measured_value = Float(nullable=True)
PropertyTypeDescription
precisionint/strDecimal places: static int (default: 2) or field path string
min_valuefloatMinimum allowed value
max_valuefloatMaximum allowed value

An amount of money. It is stored as NUMERIC, and it takes its symbol, the symbol’s side and its rounding from its currency: currency_field names the field (or path) holding the Currency the amount is in. How the figure is punctuated — decimal mark, thousands separator, digit grouping — is the reader’s language, never the currency’s, so one euro amount reads €1,234.56 in English and €1.234,56 in German (see Numbers follow the user’s language).

class GiftCard(Model):
company = ManyToOne("Company", related_name="gift_cards", on_delete="CASCADE",
required=True, default=lambda self: get_user_company(self))
# The currency the amounts are IN — required, defaulting to the card's own company's.
currency = ManyToOne("Currency", related_name="gift_cards", on_delete="RESTRICT",
required=True, default=lambda self: get_company_currency(self))
balance = Monetary(currency_field="currency")
class GiftCardTransaction(Model):
gift_card = ManyToOne("GiftCard", related_name="transactions", on_delete="CASCADE",
required=True)
# A child is in its parent's currency: derive it, don't copy it.
currency = ManyToOne("Currency", related_name="gift_card_transactions",
related_field="gift_card__currency", store=False, on_delete="SET NULL")
amount = Monetary(currency_field="currency")
PropertyTypeDescription
currency_fieldstrThe field holding the amount’s currency, or a path to it (order__currency)
min_value / max_valuefloatBounds
nullableboolBlank is distinct from zero — see below

Every amount must have a currency it can name. An amount whose currency resolves to nothing renders as a bare number at two decimals — no error, nothing logged, a figure that looks entirely plausible. And where code reads the currency too, a blank one is a wrong answer, not a cosmetic one: a gift card with no currency skips the check that it matches the order it is spent on. So every hop of currency_field must have an answer — the field is

  • required=True, or
  • has a default= — for a record that belongs to a company, default=lambda self: get_company_currency(self) (its own company’s currency; see Multi-company), or
  • calculate=d, or
  • a related_field whose own path has an answer — a line in its document’s currency, or
  • on a transient wizard, assigned in its own _default_get (the currency of the record the wizard was opened on).

./fullfinity-server check --only currency enforces this, and fails on a Monetary with no currency_field at all.

A number is zero until someone says otherwise — nullable=True

Section titled “A number is zero until someone says otherwise — nullable=True”

Integer, BigInt, Float and Monetary all follow one rule. A number nobody gave a value is 0. It defaults to 0, a cleared value is stored as 0, and its column is NOT NULL with a database DEFAULT. So arithmetic on numbers nobody filled in just works, with no None guard at every call site (line.quantity or 0 is never needed — and check --only number-guards reports one written on a number that is not nullable), and raw SQL, aggregates and reports see the same zero the ORM does.

When blank is a fact of its own, different from zero, declare nullable=True: a measurement not yet taken, an optional cap or bound, a limit that means “unlimited” when empty, a coordinate, or an id that links to a record later. It reads back as None until something writes a number, and a cleared value stays blank:

tolerance_max = Float(nullable=True) # None = no upper bound, 0.0 = bound at zero
reading = Float(nullable=True) # None = not measured, 0.0 = measured zero
usage_limit = Integer(nullable=True) # None = unlimited, 0 = none allowed
if check.reading is None:
... # nothing recorded yet — do not score it
DeclarationUnset readsCleared readsColumn
Integer() / Float() / Monetary()00NOT NULL DEFAULT 0
Float(default=1.5)1.50.0NOT NULL DEFAULT 1.5
Float(nullable=True)NoneNonenullable
Integer(required=True)— the user must answer—NOT NULL, no default
  • A required number gets no implicit zero. “Required” means someone answers; a zero filled in for them would satisfy the check without anyone answering.
  • default=None on a number is refused at load, with the spelling to use instead — blank is declared with nullable=True, so the field, the column and the form agree.
  • The form shows the difference. A nullable number that is blank reaches the form, a list and the API as blank (null), and a new record’s form starts it blank — never as 0, which would show “not set” as an answer nobody gave. Every other number is sent as 0 when unset, because that is what it holds. Give the field a placeholder saying what blank means (“Uses the contract’s pay”), since an empty box explains nothing on its own.
  • Changing your mind is free. Declaring a field nullable=True later relaxes its column on the next upgrade; removing it fills existing blanks with the default and adds the constraint. No migration hook is needed in either direction.

A boolean is never null. Declared without a default, it defaults to False, and its column is created NOT NULL — a boolean has exactly two values, so there is no third state for a column to hold. You do not need required=True to get that; required is the user-facing “you must answer this”, which a boolean always satisfies, and setting it only puts a required marker on the field in the form.

This matters when you add a boolean to a model that already has rows. The column is added nullable, backfilled with the default, and then constrained — so existing records get False rather than an absent value, and no migration hook is needed. If you want existing rows to become True instead, write a data migration for it (see Migrations); the automatic backfill only applies the declared default.

Reading a boolean therefore always gives you True or False, and a filter can rely on it: Q(is_published=False) matches every unpublished row, with no need to also test for a missing value.

Date without time:

birth_date = Date()
due_date = Date(description="Due Date")

Date with time (stored in UTC):

created_at = Datetime(default=lambda self: utc_now()) # timezone-aware UTC
scheduled_at = Datetime()

Predefined choices:

status = Selection(
choices=["Draft", "Confirmed", "Done", "Cancelled"],
default="Draft",
)
priority = Selection(
choices=["Low", "Medium", "High", "Urgent"],
default="Medium"
)
type = Selection(
choices=["Individual", "Company"],
required=True
)
PropertyTypeDescription
choiceslistList of allowed string values (required)
max_lengthintMaximum length for values (default: the length of the longest choice)

:::caution Choices are labels — write them as readable text A Selection has no separate value/label pair. The stored string is what the dropdown shows, what your Python dispatches on, what seed YAML carries, and what the frontend compares — one spelling, everywhere. So write the choice as the caption a user should read:

mode = Selection(choices=["Balance Sheet", "Profit & Loss"]) # correct
mode = Selection(choices=["balance_sheet", "profit_loss"]) # refused at import

Dispatch on that readable value directly (if report.mode == "Balance Sheet"). Never map a stored token to a display label at some boundary — that is two spellings of one concept to keep in step forever.

If you need a stable internal handle (a routing key, an external system’s identifier), that isn’t a Selection: put it in a Char code/identifier field, which is never user-displayed and where snake_case is correct.

The field refuses a choice shaped like an identifier (all-lowercase, with or without underscores) when it is declared, and so does _selection_add — the model fails to import, naming the choices. Genuine external standards keep their own spelling (HTTP 301, HTML dir ltr/rtl, unit symbols like km) and are accepted. :::

:::tip Extending Choices Extensions can add Selection choices via _selection_add, declaring what becomes of the rows if the choice later goes away with _selection_ondelete. Choices can only be added, never removed from another module’s field. See Selection Field Inheritance. :::

Store JSON/dict data:

metadata = JSON(default=dict)
settings = JSON(description="User Settings")
extra_data = JSON()

Usage:

record.metadata = {"key": "value", "nested": {"a": 1}}
await record.save()

Both in-place mutation and reassignment persist — the framework snapshots a JSON column’s loaded value so a later change is detected either way:

record.tags.append("new") # in-place mutation — detected and saved
record.settings["theme"] = "dark" # in-place key set — detected and saved
await record.save()
record.metadata = {**record.metadata, "k": "v"} # reassignment — also fine
await record.save()

Raw binary data:

data = Binary(description="Binary Data")

File attachments (stored as attachment ID):

logo = File(description="Company Logo")
document = File(description="Attached Document")
public_brochure = File(public=True, description="Brochure") # publicly accessible

Usage:

# Upload: base64 string with format: "filename;content_type;base64,data"
record.logo = "logo.png;image/png;base64,iVBORw0KGgo..."
await record.save()
OptionTypeDefaultDescription
publicboolFalseWhen True, the underlying attachment is created with is_public=True, so it is reachable without an authenticated session (e.g. logos, website assets). Leave False for anything access-controlled.
trackbool | NoneunsetRecord changes to this file in the change log. Unset means the per-type default (off for File); see change tracking.

Foreign key (many records point to one):

customer = ManyToOne(
"Contact", # Related model name
related_name="orders", # Reverse relation name
on_delete="CASCADE", # CASCADE, SET NULL, RESTRICT
required=True
)
category = ManyToOne(
"Category",
related_name="products",
on_delete="SET NULL"
)

Reverse of ManyToOne (automatically created):

# Defined on the "one" side, points to "many"
orders = OneToMany("Order", related_name="customer")

Usually you don’t define this explicitly - it’s created from related_name.

One-to-one relationship (foreign key with UNIQUE constraint):

profile = OneToOne(
"UserProfile",
related_name="user", # Reverse returns single object, not list
on_delete="CASCADE"
)
settings = OneToOne(
"UserSettings",
related_name="user",
on_delete="SET NULL"
)

Similar to ManyToOne but:

  • Has a UNIQUE constraint on the foreign key column
  • The reverse accessor returns a single object instead of a list

Many-to-many relationship:

tags = ManyToMany(
"Tag",
related_name="products",
through="fkproducttag" # Through table name
)
groups = ManyToMany(
"Group",
related_name="users",
through="fkusergroup"
)

:::note Relational defaults ManyToMany and OneToMany also support default=, but the value must be written in command notation ([["link", id]], [["create", {vals}]]), not a bare list of instances. See Relational field defaults. :::

Duplicating a record (the Duplicate action, or POST /api/clone/{model}) copies its scalar fields and its ManyToOne/ManyToMany links. For a OneToMany, “copying” means creating a new child record for every child of the original — so whether a relation is cloneable decides whether duplicating a document also manufactures new documents.

Because of that, OneToMany and OneToOne are not cloneable by default. Copying child records is opt-in:

class SaleOrder(Model):
# Composition — lines are owned parts of the order, so they come along.
lines = OneToMany("SaleOrderLine", related_name="order", clone=True)
# Everything else that points AT a sale order (invoices, subscriptions,
# deliveries) is an independent document. It takes the default and is not copied.

Use clone=True only for composition: children with no existence or workflow of their own — document lines, config sub-rows, template content. Records that merely reference the parent — anything with its own state machine, sequence number, or accounting/inventory effect — must not be cloneable, or a duplicate silently creates real business documents.

This applies to the reverse relations the framework creates automatically. Declaring ManyToOne("SaleOrder", related_name="subscriptions") on your model gives SaleOrder a subscriptions accessor that the order’s author never opted into — those are never cloned. If you need a reverse relation to be cloneable, declare the OneToMany explicitly on the parent and set clone=True.

Three further points:

  • OneToOne is not cloneable because the underlying UNIQUE constraint means copying the foreign key either fails or takes the related record away from the original.
  • Cloning follows composition all the way down. Because clone=True marks ownership and ownership is transitive, a clone recurses through cloneable relations: duplicating a survey copies its questions and each question’s answer choices. Relations left at the default are never descended into, so the copy stops at the edge of what the record owns.
  • A value the record was given is kept, even when the field is calculated. An editable calculated field (calculate= with readonly=False — a document’s currency, a line’s taxes, a negotiated price) is copied as the original’s own answer and is not re-derived after its children are copied; a non-editable calculated field is recomputed for the copy. So a credit note made by cloning a euro invoice stays in euros.
  • References inside the copy are re-pointed at the copy. If a copied child references another record that the same clone also copied — a duplicated event’s track pointing at one of its rooms — the copy is updated to reference the copied room, not the original’s. References that point outside the clone (product, currency, company) are left alone, which is correct: those are shared, not owned.

Scalar fields take clone=False too — use it for values that must not survive a copy, such as a sequence number, a posting state, or a captured signature.

active is an ordinary scalar, so it is copied like any other. Duplicating an archived record therefore produces an archived copy — created, but absent from every list until someone unarchives it. If a duplicate of a retired record should be usable straight away (usually the case: the user is duplicating it precisely to make a live one), declare active = Boolean(default=True, clone=False) on that model.

unique=True scalars need no annotation: copying a unique value can never succeed, so a clone never copies one verbatim. An optional unique field is left empty on the copy; a required one (a slug, a code) takes a derived free value — summer-fest becomes summer-fest-copy, and Summer Fest becomes Summer Fest (copy).

A calculated field is derived again on the copy — except an editable one (readonly=False), which is copied: its value is the record’s own answer (a negotiated price, a description typed over, a chosen set of taxes), and the copy keeps it exactly as a create keeps any value it is given. A credit note clones its invoice, so this is what keeps its prices.

Fields calculated from other fields:

total = Monetary(
calculate="_compute_total",
store=True # Store result in database
)
display_name = Char(
max_length=255,
calculate="get_display_name",
store=False # Calculate on-the-fly
)

See Calculated Fields for details.

Auto-compute from related model:

company_name = Char(
max_length=255,
related_field="company__name",
store=False
)
country_code = Char(
max_length=10,
related_field="address__country__code",
store=False
)

The read-through works for every field type — scalar (Char, Monetary, Selection, Boolean, Date, …) and relational (ManyToOne, OneToOne, OneToMany, ManyToMany). A relational leaf resolves to the related record (or record list); a path through a collection resolves against its first row.

Section titled “Related fields on transient models (wizards)”

A related field resolves the same way on a transient (wizard) record as on a persisted one — as long as the relation it reads through is set. A wizard takes its initial values from _default_get, so declaring the relation (typically via a default_<relation> in the opening action’s ctx) is all that’s needed:

class GlobalDiscountWizard(Model):
_transient = True
order = ManyToOne("SaleOrder", related_name="discount_wizards", on_delete="CASCADE")
# Read straight through the order relation — resolved when the wizard opens.
currency = ManyToOne("Currency", related_name="_w", on_delete="SET NULL",
related_field="order__currency", store=False)
order_subtotal = Monetary(related_field="order__subtotal", store=False, readonly=True)

Opened with {"type": "wizard", "model": "GlobalDiscountWizard", "ctx": {"default_order": order.id}}, the wizard form shows the live subtotal and currency without any _default_get override — the relation is set, so the read-through resolves. (There is no need to hand-copy the values in _default_get; do that only when the value isn’t a plain read-through of an already-set relation.)

class Contact(Model):
# Identity
name = Char(max_length=255, required=True)
email = Char(max_length=255, index=True)
phone = Char(max_length=50)
# Type
type = Selection(choices=["Individual", "Company"], default="Individual")
is_customer = Boolean(default=False)
is_supplier = Boolean(default=False)
# Relations
company = ManyToOne("Contact", related_name="contacts", on_delete="SET NULL")
tags = ManyToMany("ContactTag", related_name="contacts", through="fkcontacttag")
# Media
image = File(description="Photo")
# Timestamps
created_at = Datetime(default=lambda self: utc_now())
class Invoice(Model):
# Reference
name = Char(max_length=100, required=True)
reference = Char(max_length=100)
# Dates
invoice_date = Date(default=lambda self: date.today())
due_date = Date()
# Relations
customer = ManyToOne("Contact", related_name="invoices", required=True, on_delete="RESTRICT")
currency = ManyToOne("Currency", related_name="invoices", on_delete="RESTRICT")
# Status
status = Selection(
choices=["Draft", "Sent", "Paid", "Cancelled"],
default="Draft"
)
# Financials
subtotal = Monetary(calculate="_compute_totals", store=True, currency_field="currency")
tax_total = Monetary(calculate="_compute_totals", store=True, currency_field="currency")
total = Monetary(calculate="_compute_totals", store=True, currency_field="currency")
# Notes
notes = Text()
internal_notes = Text(description="Internal Notes")

Fields with company_scoped=True hold a separate value per company for the same record. On a regular model the field is a JSONB column on the model’s own table, keyed by company; on a transient model such as Configuration, which has no table, the values are kept in the CompanyConfig table.

class ProductCategory(Model):
name = Char(max_length=255)
# Different income account per company
income_account = ManyToOne(
"Account",
related_name="income_categories",
description="Income Account",
company_scoped=True, # one value per company, in a JSONB column
on_delete="SET NULL",
)
# Different expense account per company
expense_account = ManyToOne(
"Account",
related_name="expense_categories",
description="Expense Account",
company_scoped=True,
on_delete="SET NULL",
)
  • Storage: On a regular model, a stored field is one JSONB column on the model’s own table, mapping each company to its value. The column is created and migrated like any other
  • Transient Models: A transient model (such as Configuration) has no table, so its values are kept in CompanyConfig, keyed by field name and company
  • Read for the company in force: record.income_account answers for the company in force at the moment of the read (as_company(X), else the user’s default company) — not the one the record was loaded under. See Which company a value is read for
  • Hydration: ManyToOne/OneToOne/ManyToMany fields return fully hydrated records, not just IDs
  • Orphan Cleanup: Orphaned references are automatically cleaned up on load
  • Scalar types (Char, Text, Boolean, Integer, Float, Date, etc.)
  • ManyToOne / OneToOne (stores single ID)
  • ManyToMany (stores list of IDs)
  • OneToMany (stores its child rows — see below)

A company_scoped OneToMany persists a list of value-object rows — its children are transient records with no table of their own (the same in-memory O2M mechanism the wizards use). Each child is stored as a JSON dict of its own fields (scalars JSON-safe, ManyToOne as an id, ManyToMany as an id-list, nested OneToMany recursively); framework-managed fields (id, identifier, audit columns) and the child’s back-reference to the parent are not stored. On load the rows are rebuilt into transient children — the exact shape a form grid (widget: List) renders and edits inline.

Use this for owned config sub-rows that have no independent life. If the “children” are real records that live in their own table (stages, rules, templates), do not model them as a company_scoped OneToMany — give that model a company ManyToOne and surface it with a settingsLink or a company-scoped List. See Configuration Forms.

Filtering, sorting and grouping on a stored company_scoped field work like any other field, and compare the value for the company in force: filter(income_account=x) finds the categories whose income account for that company is x.

  • No database-level uniqueness constraints
class ConfigurationCRM(Model):
__inherit__ = "Configuration"
crm_default_stage = ManyToOne(
"CrmStage",
related_name="config_default_stage",
description="Default Lead Stage",
company_scoped=True,
on_delete="SET NULL",
)
crm_auto_assign = Boolean(
default=False,
description="Auto-assign Leads",
company_scoped=True
)

Fields support custom validators for advanced validation logic. Pass a list of validators to the validators parameter.

from fullfinity.engine.fields import (
EmailValidator,
URLValidator,
RegexValidator,
MinValueValidator,
MaxValueValidator,
MinLengthValidator,
MaxLengthValidator,
)
class Contact(Model):
email = Char(
max_length=255,
validators=[EmailValidator("Please enter a valid email")]
)
website = Char(
max_length=255,
validators=[URLValidator("Please enter a valid URL")]
)
code = Char(
max_length=20,
validators=[
RegexValidator(r"^[A-Z]{3}-\d{4}$", "Code must be XXX-0000 format")
]
)
age = Integer(
validators=[
MinValueValidator(0, "Age cannot be negative"),
MaxValueValidator(150, "Age cannot exceed 150")
]
)
username = Char(
max_length=50,
validators=[
MinLengthValidator(3, "Username must be at least 3 characters"),
MaxLengthValidator(50, "Username cannot exceed 50 characters")
]
)
ValidatorDescription
EmailValidator(message)Validates email format
URLValidator(message)Validates URL format (http/https)
RegexValidator(pattern, message)Validates against regex pattern
MinValueValidator(min, message)Validates minimum numeric value
MaxValueValidator(max, message)Validates maximum numeric value
MinLengthValidator(min, message)Validates minimum string length
MaxLengthValidator(max, message)Validates maximum string length

Create custom validators by subclassing Validator or using a callable:

from fullfinity.engine.fields import Validator, ValidationError
# Class-based validator
class PhoneValidator(Validator):
def __init__(self, message="Invalid phone number"):
self.message = message
def __call__(self, value):
if value and not value.replace("-", "").replace(" ", "").isdigit():
raise ValidationError(self.message)
# Function-based validator
def validate_positive(value):
if value is not None and value < 0:
raise ValidationError("Value must be positive")
class Order(Model):
phone = Char(max_length=20, validators=[PhoneValidator()])
quantity = Integer(validators=[validate_positive])