Fields
Basics
Every model public attributes are automatically set as table columns.
You can customize and extend the fields using ardilla.Field
and ardilla.ForeignField
.
ardilla.Field
is actually just a convenience import as it is actually pydantic.Field
.
ardilla.ForeignField
is an instance of a callable class that serves as a helper for foreign key constrains.
Usage
To extend the functionality of an ardilla.Model
import ardilla.Field
and use it on your fields.
The special keywords to use with fields are:
- default: Sets the default value for the field
- pk: sets the field as the primary key of the table
- auto: sets the field to be autogenerated on insertion. It's only valid for these field types:
- INTEGER: auto applies "autoincrement" and it's only available when used on private keys
- DATETIME, TIME and DATE: auto applies "current_timestamp", "current_date" or "current_time"
- If auto was used, then the field is automatically not required.
- unique: sets the field's value to be unique in the table, it will rise conflic errors if breached
from datetime import datetime
from ardilla import Model, Field
class User(Model):
id: int = Field(pk=True, auto=True)
name: str = Field(unique=True)
age: int # not null field
money: float = 0.0
created_date: datetime = Field(default_factory=datetime.utcnow, auto=True)
This Model will generate the following table schema:
CREATE TABLE IF NOT EXISTS user(
id INTEGER PRIMARY KEY AUTOINCREMENT,
name TEXT NOT NULL UNIQUE,
age INTEGER NOT NULL,
money REAL DEFAULT 0.0,
created_date DATETIME DEFAULT CURRENT_TIMESTAMP
);
Or, as a table:
id | name | age | money | created_date |
---|---|---|---|---|
1 | chris | 35 | -10 | 1988-05-27-7 |
Foreign key support
To set fields with foreign keys, use the foreign field helper ardilla.ForeignField
from ardilla import Model, Field, ForeignField
class Author(Model):
id: int = Field(pk=True, auto=True)
name: str
class Book(Model):
name: str
author_id: int = ForeignField(
references=Author, # the model with the referenced key
on_delete=ForeignField.CASCADE,
on_update=ForeignField.SET_NULL
)
This will generate the following schema for the Book model:
CREATE TABLE IF NOT EXISTS book(
name TEXT NOT NULL,
author_id INTEGER NOT NULL,
FOREIGN KEY (author_id) REFERENCES author(id) ON UPDATE SET NULL ON DELETE CASCADE
);
Next
To put your models to use you'll need a an engine...