Field Types API Reference

This module provides field types for defining document schemas with validation, serialization, and database conversion functionality.

Base Field Classes

class surrealengine.fields.base.Field(required=False, default=None, db_field=None, define_schema=False, indexed=False, unique=False, search=False, analyzer=None, index_with=None, comment=None)[source]

Bases: object

Base class for all field types.

This class provides the foundation for all field types in the document model. It includes methods for validation and conversion between Python and database representations.

required

Whether the field is required

default

Default value for the field

name

Name of the field (set during document class creation)

db_field

Name of the field in the database

owner_document

The document class that owns this field

define_schema

Whether to define this field in the schema (even for SCHEMALESS tables)

__init__(required=False, default=None, db_field=None, define_schema=False, indexed=False, unique=False, search=False, analyzer=None, index_with=None, comment=None)[source]

Initialize a new Field.

Parameters:
  • required (bool) – Whether the field is required

  • default (Any) – Default value for the field

  • db_field (str | None) – Name of the field in the database (defaults to the field name)

  • define_schema (bool) – Whether to define this field in the schema (even for SCHEMALESS tables)

  • indexed (bool) – Whether the field should be indexed

  • unique (bool) – Whether the index should enforce uniqueness

  • search (bool) – Whether the index is a search index

  • analyzer (str | None) – Analyzer to use for search indexes

  • index_with (List[str] | None) – List of other field names to include in the index

validate(value)[source]

Validate the field value.

This method checks if the value is valid for this field type. Subclasses should override this method to provide type-specific validation.

Parameters:

value (Any) – The value to validate

Returns:

The validated value

Raises:
  • ValidationError – If the value is invalid for this field type

  • ValueError – If the value is None and the field is required

Return type:

Any

Examples

Basic validation:

>>> field = StringField(required=True)
>>> field.validate("hello")
'hello'

Required field validation:

>>> field = StringField(required=True)
>>> field.validate(None)
Traceback (most recent call last):
ValueError: Field 'field_name' is required
to_db(value)[source]

Convert Python value to database representation.

This method converts a Python value to a representation that can be stored in the database. Subclasses should override this method to provide type-specific conversion.

Parameters:

value (Any) – The Python value to convert

Returns:

The database representation of the value

Return type:

Any

Examples

Basic to_db conversion:

>>> field = Field()
>>> field.to_db("hello")
'hello'

None value handling:

>>> field.to_db(None)
from_db(value)[source]

Convert database value to Python representation.

This method converts a value from the database to a Python value. Subclasses should override this method to provide type-specific conversion.

Parameters:

value (Any) – The database value to convert

Returns:

The Python representation of the value

Return type:

Any

Examples

Basic from_db conversion:

>>> field = Field()
>>> field.from_db("hello")
'hello'

None value handling:

>>> field.from_db(None)
get_surreal_type()[source]

Return the SurrealQL type name for this field.

This method returns the appropriate SurrealQL type name that corresponds to this field type. Subclasses should override this method to provide their specific SurrealQL type.

Returns:

The SurrealQL type name as a string

Return type:

str

Examples

>>> field = Field()
>>> field.get_surreal_type()
'any'
cast_to_surreal_type()[source]

Return SurrealQL type casting syntax.

This method returns the SurrealQL type casting syntax for this field, which can be used in queries to explicitly cast values to the correct type.

Returns:

The SurrealQL type casting syntax

Return type:

str

Examples

>>> field = Field()
>>> field.cast_to_surreal_type()
'<any>'
class surrealengine.fields.id.RecordIDField(table_name=None, **kwargs)[source]

Bases: Field

RecordID field type.

This field type stores record IDs and provides validation and conversion between Python values and SurrealDB record ID format.

A RecordID consists of a table name and a unique identifier, formatted as table:id. This field can accept a string in this format, or a tuple/list with the table name and ID.

Example:

class Reference(Document):
    target = RecordIDField()
__init__(table_name=None, **kwargs)[source]

Initialize a new RecordIDField.

Parameters:
  • table_name (str | None) – Optional table name to enforce for this field

  • **kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the record ID.

This method checks if the value is a valid record ID.

Parameters:

value (Any) – The value to validate

Returns:

The validated record ID

Raises:
  • TypeError – If the value cannot be converted to a record ID

  • ValueError – If the record ID format is invalid

Return type:

str | None

to_db(value)[source]

Convert Python value to database representation.

This method converts a Python value to a record ID for storage in the database.

Parameters:

value (Any) – The Python value to convert

Returns:

The record ID for the database

Return type:

str | None

from_db(value)[source]

Convert database value to Python representation.

This method converts a record ID from the database to a Python representation.

Parameters:

value (Any) – The database value to convert

Returns:

The Python representation of the record ID

Return type:

str | None

Scalar Fields

class surrealengine.fields.scalar.StringField(min_length=None, max_length=None, regex=None, choices=None, **kwargs)[source]

Bases: Field

String field type.

This field type stores string values and provides validation for minimum length, maximum length, and regex pattern matching.

min_length

Minimum length of the string

max_length

Maximum length of the string

regex

Regular expression pattern to match

Examples

Basic string field:

>>> name = StringField(required=True)

String with length constraints:

>>> title = StringField(max_length=100, required=True)
>>> username = StringField(min_length=3, max_length=20)

String with regex validation:

>>> email = StringField(regex=r'^[^@]+@[^@]+\.[^@]+$')
>>> slug = StringField(regex=r'^[a-z0-9-]+$')

Indexed string field:

>>> name = StringField(indexed=True, unique=True)
>>> category = StringField(indexed=True)

String field with choices:

>>> status = StringField(choices=['active', 'inactive', 'pending'])

String field for schema definition:

>>> name = StringField(required=True, define_schema=True)
__init__(min_length=None, max_length=None, regex=None, choices=None, **kwargs)[source]

Initialize a new StringField.

Parameters:
  • min_length (int | None) – Minimum length of the string

  • max_length (int | None) – Maximum length of the string

  • regex (str | None) – Regular expression pattern to match

  • choices (list | None) – List of valid choices for this field

  • required – Whether the field is required (default: False)

  • default – Default value for the field

  • db_field – Name of the field in the database (defaults to the field name)

  • define_schema – Whether to define this field in the schema (even for SCHEMALESS tables)

  • indexed – Whether the field should be indexed (default: False)

  • unique – Whether the index should enforce uniqueness (default: False)

  • search – Whether the index is a search index (default: False)

  • analyzer – Analyzer to use for search indexes

  • index_with – List of other field names to include in the index

validate(value)[source]

Validate the string value.

This method checks if the value is a valid string and meets the constraints for minimum length, maximum length, and regex pattern.

Parameters:

value (Any) – The value to validate

Returns:

The validated string value

Raises:
  • TypeError – If the value is not a string

  • ValueError – If the value does not meet the constraints

Return type:

str | None

class surrealengine.fields.scalar.IntField(**kwargs)[source]

Bases: NumberField

Integer field type.

This field type stores integer values and provides validation to ensure the value is an integer.

Examples

Basic integer field:

>>> age = IntField(min_value=0)
>>> count = IntField(default=0)

Integer with constraints:

>>> priority = IntField(min_value=1, max_value=5, default=3)
>>> year = IntField(min_value=1900, max_value=2100)

Required integer:

>>> user_id = IntField(required=True)
>>> views = IntField(default=0, min_value=0)
__init__(**kwargs)[source]

Initialize a new IntField.

Parameters:
  • min_value – Minimum allowed value

  • max_value – Maximum allowed value

  • required – Whether the field is required (default: False)

  • default – Default value for the field

  • db_field – Name of the field in the database (defaults to the field name)

  • define_schema – Whether to define this field in the schema (even for SCHEMALESS tables)

  • indexed – Whether the field should be indexed (default: False)

  • unique – Whether the index should enforce uniqueness (default: False)

  • search – Whether the index is a search index (default: False)

  • analyzer – Analyzer to use for search indexes

  • index_with – List of other field names to include in the index

validate(value)[source]

Validate the integer value.

This method checks if the value is a valid integer.

Parameters:

value (Any) – The value to validate

Returns:

The validated integer value

Raises:

TypeError – If the value is not an integer

Return type:

int | None

to_db(value)[source]

Convert Python value to database representation.

This method converts a Python value to an integer for storage in the database.

Parameters:

value (Any) – The Python value to convert

Returns:

The integer value for the database

Return type:

int | None

class surrealengine.fields.scalar.FloatField(**kwargs)[source]

Bases: NumberField

Float field type.

This field type stores floating-point values and provides validation to ensure the value can be converted to a float.

Examples

Basic float field:

>>> price = FloatField(min_value=0)
>>> rating = FloatField(min_value=0.0, max_value=5.0)

Float with precision:

>>> estimated_hours = FloatField(min_value=0.1)
>>> percentage = FloatField(min_value=0.0, max_value=100.0)

Financial data:

>>> balance = FloatField(default=0.0)
>>> tax_rate = FloatField(min_value=0.0, max_value=1.0)
__init__(**kwargs)[source]

Initialize a new FloatField.

Parameters:
  • min_value – Minimum allowed value

  • max_value – Maximum allowed value

  • required – Whether the field is required (default: False)

  • default – Default value for the field

  • db_field – Name of the field in the database (defaults to the field name)

  • define_schema – Whether to define this field in the schema (even for SCHEMALESS tables)

  • indexed – Whether the field should be indexed (default: False)

  • unique – Whether the index should enforce uniqueness (default: False)

  • search – Whether the index is a search index (default: False)

  • analyzer – Analyzer to use for search indexes

  • index_with – List of other field names to include in the index

validate(value)[source]

Validate the float value.

This method checks if the value can be converted to a float.

Parameters:

value (Any) – The value to validate

Returns:

The validated float value

Raises:

TypeError – If the value cannot be converted to a float

Return type:

float | None

class surrealengine.fields.scalar.NumberField(min_value=None, max_value=None, **kwargs)[source]

Bases: Field

Base class for numeric fields.

This field type is the base class for all numeric field types. It provides validation for minimum and maximum values.

min_value

Minimum allowed value

max_value

Maximum allowed value

Examples

Basic number field:

>>> score = NumberField()

Number with range constraints:

>>> priority = NumberField(min_value=1, max_value=5, default=3)
>>> percentage = NumberField(min_value=0, max_value=100)
>>> age = NumberField(min_value=0)

Required number field:

>>> price = NumberField(min_value=0, required=True)
__init__(min_value=None, max_value=None, **kwargs)[source]

Initialize a new NumberField.

Parameters:
  • min_value (int | float | None) – Minimum allowed value

  • max_value (int | float | None) – Maximum allowed value

  • required – Whether the field is required (default: False)

  • default – Default value for the field

  • db_field – Name of the field in the database (defaults to the field name)

  • define_schema – Whether to define this field in the schema (even for SCHEMALESS tables)

  • indexed – Whether the field should be indexed (default: False)

  • unique – Whether the index should enforce uniqueness (default: False)

  • search – Whether the index is a search index (default: False)

  • analyzer – Analyzer to use for search indexes

  • index_with – List of other field names to include in the index

validate(value)[source]

Validate the numeric value.

This method checks if the value is a valid number and meets the constraints for minimum and maximum values.

Parameters:

value (Any) – The value to validate

Returns:

The validated numeric value

Raises:
  • TypeError – If the value is not a number

  • ValueError – If the value does not meet the constraints

Return type:

int | float | None

class surrealengine.fields.scalar.BooleanField(**kwargs)[source]

Bases: Field

Boolean field type.

This field type stores boolean values and provides validation to ensure the value is a boolean.

Examples

Basic boolean field:

>>> active = BooleanField(default=True)
>>> completed = BooleanField(default=False)

Required boolean:

>>> is_primary_author = BooleanField(default=True)
>>> published = BooleanField(default=False)

Boolean with indexing:

>>> active = BooleanField(default=True, indexed=True)
__init__(**kwargs)[source]

Initialize a new BooleanField.

Parameters:
  • required – Whether the field is required (default: False)

  • default – Default value for the field

  • db_field – Name of the field in the database (defaults to the field name)

  • define_schema – Whether to define this field in the schema (even for SCHEMALESS tables)

  • indexed – Whether the field should be indexed (default: False)

  • unique – Whether the index should enforce uniqueness (default: False)

  • search – Whether the index is a search index (default: False)

  • analyzer – Analyzer to use for search indexes

  • index_with – List of other field names to include in the index

validate(value)[source]

Validate the boolean value.

This method checks if the value is a valid boolean.

Parameters:

value (Any) – The value to validate

Returns:

The validated boolean value

Raises:

TypeError – If the value is not a boolean

Return type:

bool | None

class surrealengine.fields.specialized.DecimalField(**kwargs)[source]

Bases: NumberField

Decimal field type.

This field type stores decimal values with arbitrary precision using Python’s Decimal class. It provides validation to ensure the value is a valid decimal.

__init__(**kwargs)[source]

Initialize a new DecimalField.

Parameters:

**kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the decimal value.

This method checks if the value is a valid decimal or can be converted to a decimal.

Parameters:

value (Any) – The value to validate

Returns:

The validated decimal value

Raises:

TypeError – If the value cannot be converted to a decimal

Return type:

Decimal | None

to_db(value)[source]

Convert Python decimal to database representation.

This method converts a Python Decimal object to a string for storage in the database to preserve precision.

Parameters:

value (Any) – The Python Decimal to convert

Returns:

The string representation for the database

Return type:

str | None

from_db(value)[source]

Convert database value to Python Decimal.

This method converts a value from the database to a Python Decimal object.

Parameters:

value (Any) – The database value to convert

Returns:

The Python Decimal object

Return type:

Decimal | None

Collection Fields

class surrealengine.fields.collection.ListField(field_type=None, max_items=None, surreal_functions=None, **kwargs)[source]

Bases: Field

List field type.

This field type stores lists of values and provides validation and conversion for the items in the list. The items can be of a specific field type, which is used to validate and convert each item.

field_type

The field type for items in the list

__init__(field_type=None, max_items=None, surreal_functions=None, **kwargs)[source]

Initialize a new ListField.

Parameters:
  • field_type (Field | None) – The field type for items in the list

  • max_items (int | None) – Maximum number of items allowed in the list

  • surreal_functions (List[str] | None) – List of SurrealQL array functions to apply (array::sort, array::unique, etc.)

  • **kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the list value.

This method checks if the value is a valid list and validates each item in the list using the field_type if provided.

Parameters:

value (Any) – The value to validate

Returns:

The validated list value

Raises:
  • TypeError – If the value is not a list

  • ValueError – If an item in the list fails validation or max_items is exceeded

Return type:

List[Any] | None

to_db(value)[source]

Convert Python list to database representation.

This method converts a Python list to a database representation by converting each item using the field_type if provided.

Parameters:

value (List[Any] | None) – The Python list to convert

Returns:

The database representation of the list

Return type:

List[Any] | None

from_db(value)[source]

Convert database list to Python representation.

This method converts a database list to a Python representation by converting each item using the field_type if provided.

Parameters:

value (List[Any] | None) – The database list to convert

Returns:

The Python representation of the list

Return type:

List[Any] | None

class surrealengine.fields.collection.DictField(field_type=None, schema=None, **kwargs)[source]

Bases: Field

Dict field type.

This field type stores dictionaries of values and provides validation and conversion for the values in the dictionary. The values can be of a specific field type, which is used to validate and convert each value.

field_type

The field type for values in the dictionary

__init__(field_type=None, schema=None, **kwargs)[source]

Initialize a new DictField.

Parameters:
  • field_type (Field | None) – The field type for values in the dictionary

  • schema (Dict[str, Field] | None) – Optional schema defining specific field types for dictionary keys

  • **kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the dictionary value.

This method checks if the value is a valid dictionary and validates each value in the dictionary using the field_type if provided, or using specific field types from schema if available.

Parameters:

value (Any) – The value to validate

Returns:

The validated dictionary value

Raises:
  • TypeError – If the value is not a dictionary

  • ValueError – If a value in the dictionary fails validation

Return type:

Any

to_db(value)[source]

Convert Python dictionary to database representation.

This method converts a Python dictionary to a database representation by converting each value using the field_type if provided.

Parameters:

value (Dict[str, Any] | None) – The Python dictionary to convert

Returns:

The database representation of the dictionary

Return type:

Dict[str, Any] | None

from_db(value)[source]

Convert database dictionary to Python representation.

This method converts a database dictionary to a Python representation by converting each value using the field_type if provided.

Parameters:

value (Dict[str, Any] | None) – The database dictionary to convert

Returns:

The Python representation of the dictionary

Return type:

Dict[str, Any] | None

class surrealengine.fields.collection.SetField(field_type=None, max_items=None, surreal_functions=None, **kwargs)[source]

Bases: ListField

Set field type.

This field type stores sets of unique values and provides validation and conversion for the items in the set. Values are automatically deduplicated.

Example

class User(Document):

tags = SetField(StringField())

validate(value)[source]

Validate the list value and ensure uniqueness.

This method checks if the value is a valid list and validates each item in the list using the field_type if provided. It also ensures that all items in the list are unique.

Parameters:

value (Any) – The value to validate

Returns:

The validated and deduplicated list value

Return type:

List[Any] | None

to_db(value)[source]

Convert Python list to database representation with deduplication.

DateTime Fields

class surrealengine.fields.datetime.DateTimeField(**kwargs)[source]

Bases: Field

DateTime field type.

This field type stores datetime values and provides validation and conversion between Python datetime objects and SurrealDB datetime format.

SurrealDB v2.0.0+ requires datetime values to have a d prefix or be cast as <datetime>. This field handles the conversion automatically, so you can use standard Python datetime objects in your code.

Example:

class Event(Document):
    created_at = DateTimeField(default=datetime.datetime.now)
    scheduled_for = DateTimeField()

# Python datetime objects are automatically converted to SurrealDB format
event = Event(scheduled_for=datetime.datetime.now() + datetime.timedelta(days=7))
await event.save()
__init__(**kwargs)[source]

Initialize a new DateTimeField.

Parameters:

**kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the datetime value.

Accepts datetime, Datetime, ISO strings (with optional Z or space separator), Surreal d’…’ literals, and epoch seconds/milliseconds (int/float).

to_db(value)[source]

Convert Python datetime to database representation.

This method converts a Python datetime object (or ISO-like string) to a SurrealDB datetime type using the SDK’s Datetime wrapper so that schemafull TYPE datetime is satisfied. If a naive datetime is provided, assume UTC to avoid ambiguity.

from_db(value)[source]

Convert database value to Python datetime.

Accepts Datetime, Surreal d’…’ literal strings, ISO strings (with optional Z), or datetime instances. Returns a Python datetime (timezone-aware if source has offset).

class surrealengine.fields.datetime.DurationField(**kwargs)[source]

Bases: Field

Duration field type.

This field type stores durations of time and provides validation and conversion between Python timedelta objects and SurrealDB duration strings.

__init__(**kwargs)[source]

Initialize a new DurationField.

Parameters:

**kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the duration value.

This method checks if the value is a valid timedelta or can be converted to a timedelta from a string.

Parameters:

value (Any) – The value to validate

Returns:

The validated timedelta value

Raises:

TypeError – If the value cannot be converted to a timedelta

Return type:

timedelta | None

to_db(value)[source]

Convert Python timedelta to database representation.

This method converts a Python timedelta object to a SurrealDB Duration object for storage in the database.

Parameters:

value (Any) – The Python timedelta to convert

Returns:

The SurrealDB Duration object for the database

Return type:

Any | None

from_db(value)[source]

Convert database value to Python timedelta.

This method converts a SurrealDB duration string from the database to a Python timedelta object.

Parameters:

value (Any) – The database value to convert

Returns:

The Python timedelta object

Return type:

timedelta | None

class surrealengine.fields.datetime.TimeSeriesField(**kwargs)[source]

Bases: DateTimeField

Field for time series data.

This field type extends DateTimeField and adds support for time series data. It can be used to store timestamps for time series data and supports additional metadata for time series operations.

Example

class SensorReading(Document):

timestamp = TimeSeriesField(index=True) value = FloatField()

class Meta:

time_series = True time_field = “timestamp”

__init__(**kwargs)[source]

Initialize a new TimeSeriesField.

Parameters:

**kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the timestamp value.

This method checks if the value is a valid timestamp for time series data.

Parameters:

value (Any) – The value to validate

Returns:

The validated timestamp value

Return type:

datetime | None

Reference Fields

class surrealengine.fields.reference.ReferenceField(document_type, **kwargs)[source]

Bases: Field

Reference to another document.

This field type stores references to other documents in the database. It can accept a document instance, an ID string, or a dictionary with an ID.

document_type

The type of document being referenced

Examples

Basic reference field:

>>> author = ReferenceField(User, required=True)
>>> category = ReferenceField(Category)

Optional reference:

>>> parent = ReferenceField(Comment)  # Self-reference
>>> reviewer = ReferenceField(User)

Reference with schema definition:

>>> resident = ReferenceField(Person, define_schema=True)
>>> organization = ReferenceField(Organization, indexed=True)

Multiple references in a document:

>>> class Post(Document):
...     author = ReferenceField(User, required=True)
...     category = ReferenceField(Category)
...     reviewer = ReferenceField(User)
__init__(document_type, **kwargs)[source]

Initialize a new ReferenceField.

Parameters:
  • document_type (Type) – The type of document being referenced

  • required – Whether the field is required (default: False)

  • default – Default value for the field

  • db_field – Name of the field in the database (defaults to the field name)

  • define_schema – Whether to define this field in the schema (even for SCHEMALESS tables)

  • indexed – Whether the field should be indexed (default: False)

  • unique – Whether the index should enforce uniqueness (default: False)

  • search – Whether the index is a search index (default: False)

  • analyzer – Analyzer to use for search indexes

  • index_with – List of other field names to include in the index

validate(value)[source]

Validate the reference value.

This method checks if the value is a valid reference to another document. It accepts a document instance, an ID string, a dictionary with an ID, or a RecordID object.

Parameters:

value (Any) – The value to validate

Returns:

The validated reference value

Raises:
  • TypeError – If the value is not a valid reference

  • ValueError – If the referenced document is not saved

Return type:

Any

to_db(value)[source]

Convert Python reference to database representation.

This method converts a Python reference (document instance, ID string, dictionary with an ID, or RecordID object) to a database representation.

Parameters:

value (Any) – The Python reference to convert

Returns:

The database representation of the reference

Raises:

ValueError – If the referenced document is not saved

Return type:

str | None

from_db(value, dereference=False)[source]

Convert database reference to Python representation.

This method converts a database reference to a Python representation. If the value is already a resolved document (from FETCH), return it as is. If dereference is False, it returns the string reference as is. If dereference is True but value is still a string, fetch the referenced document.

Parameters:
  • value (Any) – The database reference to convert

  • dereference (bool) – Whether to dereference the reference (default: False)

Returns:

The Python representation of the reference

Return type:

Any

class surrealengine.fields.reference.RelationField(to_document, **kwargs)[source]

Bases: Field

Field representing a relation between documents.

This field type stores relations between documents in the database. It can accept a document instance, an ID string, or a dictionary with an ID.

to_document

The type of document being related to

__init__(to_document, **kwargs)[source]

Initialize a new RelationField.

Parameters:
  • to_document (Type) – The type of document being related to

  • required – Whether the field is required (default: False)

  • default – Default value for the field

  • db_field – Name of the field in the database (defaults to the field name)

  • define_schema – Whether to define this field in the schema (even for SCHEMALESS tables)

  • indexed – Whether the field should be indexed (default: False)

  • unique – Whether the index should enforce uniqueness (default: False)

  • search – Whether the index is a search index (default: False)

  • analyzer – Analyzer to use for search indexes

  • index_with – List of other field names to include in the index

validate(value)[source]

Validate the relation value.

This method checks if the value is a valid relation to another document. It accepts a document instance, an ID string, or a dictionary with an ID.

Parameters:

value (Any) – The value to validate

Returns:

The validated relation value

Raises:

TypeError – If the value is not a valid relation

Return type:

Any

to_db(value)[source]

Convert Python relation to database representation.

This method converts a Python relation (document instance, ID string, or dictionary with an ID) to a database representation.

Parameters:

value (Any) – The Python relation to convert

Returns:

The database representation of the relation

Raises:

ValueError – If the related document is not saved

Return type:

str | None

from_db(value, dereference=False)[source]

Convert database relation to Python representation.

This method converts a database relation to a Python representation. If the value is already a resolved document (from FETCH), return it as is. If dereference is False, it returns the string reference as is. If dereference is True but value is still a string, fetch the related document.

Parameters:
  • value (Any) – The database relation to convert

  • dereference (bool) – Whether to dereference the relation (default: False)

Returns:

The Python representation of the relation

Return type:

Any

Get documents related through this relation field.

This method retrieves documents related to the given instance through this relation field. It uses the RelationQuerySet to get related documents.

Parameters:

instance (Any) – The instance to get related documents for

Returns:

List of related documents

Raises:

ValueError – If the instance is not saved

Return type:

List[Any]

Get documents related through this relation field synchronously.

This method retrieves documents related to the given instance through this relation field. It uses the RelationQuerySet to get related documents.

Parameters:

instance (Any) – The instance to get related documents for

Returns:

List of related documents

Raises:

ValueError – If the instance is not saved

Return type:

List[Any]

Specialized Fields

class surrealengine.fields.specialized.EmailField(**kwargs)[source]

Bases: StringField

Email field type.

This field type stores email addresses and provides validation to ensure the value is a valid email address.

Example:

class User(Document):
    email = EmailField(required=True)
__init__(**kwargs)[source]

Initialize a new EmailField.

Parameters:

**kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the email address.

This method checks if the value is a valid email address.

Parameters:

value (Any) – The value to validate

Returns:

The validated email address

Raises:

ValueError – If the email address is invalid

Return type:

str | None

class surrealengine.fields.specialized.URLField(default_scheme='https', allow_host_only=True, allowed_schemes=None, **kwargs)[source]

Bases: StringField

Enhanced URL field type with urllib integration.

This field type stores URLs and provides validation using urllib.parse. It also provides convenient access to URL components and allows flexible URL formats including host-only URLs.

Features: - Access URL components via properties (.scheme, .host, .path, .query, etc.) - Allow host-only URLs (automatically adds scheme) - Robust URL validation using urllib.parse - Flexible scheme handling (http/https/ftp/etc.)

Example:

class Website(Document):
    url = URLField(default_scheme='https', allow_host_only=True)

# Usage examples:
site = Website()
site.url = "example.com"  # Auto-converts to "https://example.com"
print(site.url.host)      # "example.com"
print(site.url.scheme)    # "https"
print(site.url.port)      # None

site.url = "https://api.example.com:8080/v1/users?active=true"
print(site.url.host)      # "api.example.com"
print(site.url.port)      # 8080
print(site.url.path)      # "/v1/users"
print(site.url.query)     # "active=true"
__init__(default_scheme='https', allow_host_only=True, allowed_schemes=None, **kwargs)[source]

Initialize a new enhanced URLField.

Parameters:
  • default_scheme (str) – Default scheme to use for host-only URLs

  • allow_host_only (bool) – Whether to allow host-only URLs (will add default_scheme)

  • allowed_schemes (List[str] | None) – List of allowed schemes (None = allow all)

  • **kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate and normalize the URL.

This method uses urllib.parse for robust URL validation and automatically adds schemes to host-only URLs if allowed.

Parameters:

value (Any) – The value to validate

Returns:

The validated and normalized URL

Raises:

ValueError – If the URL is invalid

Return type:

str | None

property scheme: str | None

Get the URL scheme (protocol).

property host: str | None

Get the URL host/domain.

property hostname: str | None

Alias for host property.

property port: int | None

Get the URL port.

property path: str

Get the URL path.

property query: str

Get the URL query string.

property fragment: str

Get the URL fragment (hash).

property netloc: str

port).

Type:

Get the network location (host

property params: str

Get the URL parameters.

get_query_params()[source]

Parse query string into a dictionary.

Returns:

Dictionary of query parameters

Return type:

Dict[str, str]

get_query_param(param_name, default=None)[source]

Get a specific query parameter value.

Parameters:
  • param_name (str) – Name of the parameter to get

  • default (Any) – Default value if parameter not found

Returns:

Parameter value or default

Return type:

Any

is_secure()[source]

Check if the URL uses a secure scheme (https/ftps).

get_base_url()[source]

Get the base URL (scheme + netloc).

Returns:

Base URL string

Return type:

str

to_db(value)[source]

Convert Python URL to database representation.

Parameters:

value (Any) – The Python URL to convert

Returns:

The string representation for the database

Return type:

str | None

from_db(value)[source]

Convert database value to Python URL.

Parameters:

value (Any) – The database value to convert

Returns:

The Python URL string with parsed components available

Return type:

str | None

__str__()[source]

String representation of the URL.

__repr__()[source]

Detailed representation of the URL.

class surrealengine.fields.specialized.IPAddressField(ipv4_only=False, ipv6_only=False, version=None, **kwargs)[source]

Bases: StringField

IP address field type.

This field type stores IP addresses and provides validation to ensure the value is a valid IPv4 or IPv6 address.

Example:

class Server(Document):
    ip_address = IPAddressField(required=True)
    ip_v4 = IPAddressField(ipv4_only=True)
    ip_v6 = IPAddressField(ipv6_only=True)
__init__(ipv4_only=False, ipv6_only=False, version=None, **kwargs)[source]

Initialize a new IPAddressField.

Parameters:
  • ipv4_only (bool) – Whether to only allow IPv4 addresses

  • ipv6_only (bool) – Whether to only allow IPv6 addresses

  • version (str) – IP version to validate (‘ipv4’, ‘ipv6’, or ‘both’)

  • **kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the IP address.

This method checks if the value is a valid IP address.

Parameters:

value (Any) – The value to validate

Returns:

The validated IP address

Raises:

ValueError – If the IP address is invalid

Return type:

str | None

class surrealengine.fields.specialized.SlugField(**kwargs)[source]

Bases: StringField

Slug field type.

This field type stores slugs (URL-friendly strings) and provides validation to ensure the value is a valid slug.

Example:

class Article(Document):
    slug = SlugField(required=True)
__init__(**kwargs)[source]

Initialize a new SlugField.

Parameters:

**kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the slug.

This method checks if the value is a valid slug.

Parameters:

value (Any) – The value to validate

Returns:

The validated slug

Raises:

ValueError – If the slug is invalid

Return type:

str | None

class surrealengine.fields.specialized.ChoiceField(choices, **kwargs)[source]

Bases: Field

Choice field type.

This field type stores values from a predefined set of choices and provides validation to ensure the value is one of the allowed choices.

Example:

class Product(Document):
    status = ChoiceField(choices=['active', 'inactive', 'discontinued'])
__init__(choices, **kwargs)[source]

Initialize a new ChoiceField.

Parameters:
  • choices (List[str | tuple]) – List of allowed choices. Each choice can be a string or a tuple of (value, display_name).

  • **kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the choice value.

This method checks if the value is one of the allowed choices.

Parameters:

value (Any) – The value to validate

Returns:

The validated choice value

Raises:

ValueError – If the value is not one of the allowed choices

Return type:

str | None

Geometry Fields

class surrealengine.fields.geometry.GeometryField(required=False, **kwargs)[source]

Bases: Field

Field for handling geometric data in SurrealDB.

This field validates and processes geometric data according to SurrealDB’s geometry specification. It supports various geometry types including Point, LineString, Polygon, MultiPoint, MultiLineString, and MultiPolygon.

required

Whether the field is required. Defaults to False.

Type:

bool

Example:

class Location(Document):
    point = GeometryField()

# Using GeometryPoint for precise coordinate handling
from surrealengine.geometry import GeometryPoint
loc = Location(point=GeometryPoint([-122.4194, 37.7749]))
__init__(required=False, **kwargs)[source]

Initialize a GeometryField.

Parameters:
  • required (bool, optional) – Whether this field is required. Defaults to False.

  • **kwargs – Additional field options to be passed to the parent Field class.

validate(value)[source]

Validate geometry data.

Ensures the geometry data follows SurrealDB’s expected format with proper structure and coordinates. Does not modify the numeric values to preserve SurrealDB’s native geometry handling.

Parameters:

value – The geometry value to validate. Can be a GeometryPoint object or a dict with ‘type’ and ‘coordinates’ fields.

Returns:

The validated geometry data.

Return type:

dict

Raises:

ValidationError – If the geometry data is invalid or improperly formatted.

Additional Fields

class surrealengine.fields.additional.OptionField(field_type, **kwargs)[source]

Bases: Field

Option field type.

This field type makes a field optional and guarantees it to be either None or a value of the specified type.

field_type

The field type for the value when not None

__init__(field_type, **kwargs)[source]

Initialize a new OptionField.

Parameters:
  • field_type (Field) – The field type for the value when not None

  • **kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the option value.

This method checks if the value is None or a valid value for the field_type.

Parameters:

value (Any) – The value to validate

Returns:

The validated value

Raises:

ValueError – If the value is not None and fails validation for field_type

Return type:

Any

to_db(value)[source]

Convert Python value to database representation.

This method converts a Python value to a database representation using the field_type’s to_db method if the value is not None.

Parameters:

value (Any) – The Python value to convert

Returns:

The database representation of the value

Return type:

Any

from_db(value)[source]

Convert database value to Python representation.

This method converts a database value to a Python representation using the field_type’s from_db method if the value is not None.

Parameters:

value (Any) – The database value to convert

Returns:

The Python representation of the value

Return type:

Any

class surrealengine.fields.specialized.LiteralField(allowed_values, **kwargs)[source]

Bases: Field

Field for union/enum-like values.

Allows a field to accept multiple different types or specific values, similar to a union or enum type in other languages.

Example

class Product(Document):

status = LiteralField([“active”, “discontinued”, “out_of_stock”]) id_or_name = LiteralField([IntField(), StringField()])

__init__(allowed_values, **kwargs)[source]

Initialize a new LiteralField.

Parameters:
  • allowed_values (List[Any]) – List of allowed values or field types

  • **kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate that the value is one of the allowed values or types.

Parameters:

value (Any) – The value to validate

Returns:

The validated value

Raises:

ValidationError – If the value is not one of the allowed values or types

Return type:

Any

to_db(value)[source]

Convert Python value to database representation.

This method converts a Python value to a database representation by using the appropriate field type if the value is not a literal.

Parameters:

value (Any) – The Python value to convert

Returns:

The database representation of the value

Return type:

Any

from_db(value)[source]

Convert database value to Python representation.

This method converts a database value to a Python representation by using the appropriate field type if the value is not a literal.

Parameters:

value (Any) – The database value to convert

Returns:

The Python representation of the value

Return type:

Any

class surrealengine.fields.additional.RangeField(min_type, max_type=None, **kwargs)[source]

Bases: Field

Field for storing ranges of values.

This field type stores ranges of values with minimum and maximum bounds. It supports various types for the bounds, such as numbers, strings, and dates.

Example

class PriceRange(Document):

price_range = RangeField(min_type=FloatField(), max_type=FloatField()) age_range = RangeField(min_type=IntField(), max_type=IntField())

__init__(min_type, max_type=None, **kwargs)[source]

Initialize a new RangeField.

Parameters:
  • min_type (Field) – The field type for the minimum value

  • max_type (Field) – The field type for the maximum value (defaults to same as min_type)

  • **kwargs (Any) – Additional arguments to pass to the parent class

validate(value)[source]

Validate the range value.

This method checks if the value is a valid range with minimum and maximum values that can be validated by the respective field types.

Parameters:

value (Any) – The value to validate

Returns:

The validated range value

Raises:

ValidationError – If the value is not a valid range

Return type:

Dict[str, Any] | None

to_db(value)[source]

Convert Python range to database representation.

Parameters:

value (Dict[str, Any] | None) – The Python range to convert

Returns:

The database representation of the range

Return type:

Dict[str, Any] | None

from_db(value)[source]

Convert database range to Python representation.

Parameters:

value (Dict[str, Any] | None) – The database range to convert

Returns:

The Python representation of the range

Return type:

Dict[str, Any] | None

class surrealengine.fields.additional.FutureField(computation_expression, **kwargs)[source]

Bases: Field

Field for future (computed) values.

This field type represents a computed value in SurrealDB that is calculated at query time rather than stored in the database. It uses SurrealDB’s <future> syntax to define a computation expression.

computation_expression

The SurrealDB expression to compute the value

__init__(computation_expression, **kwargs)[source]

Initialize a new FutureField.

Parameters:
  • computation_expression (str) – The SurrealDB expression to compute the value

  • **kwargs (Any) – Additional arguments to pass to the parent class

to_db(value)[source]

Convert to SurrealDB future syntax.

This method returns the SurrealDB <future> syntax with the computation expression, regardless of the input value.

Parameters:

value (Any) – The input value (ignored)

Returns:

The SurrealDB future syntax string

Return type:

str

Usage Examples

Basic Field Usage

from surrealengine import Document, StringField, IntField, EmailField

class User(Document):
    name = StringField(required=True, max_length=100)
    age = IntField(min_value=0, max_value=150)
    email = EmailField(unique=True, indexed=True)

Field Validation

# Automatic validation on assignment
user = User()
user.email = "invalid-email"  # Raises ValidationError
user.email = "user@example.com"  # Valid

# Custom validation
class Product(Document):
    name = StringField(required=True)
    price = DecimalField(min_value=0, max_digits=10, decimal_places=2)

Reference Fields

class Author(Document):
    name = StringField(required=True)

class Book(Document):
    title = StringField(required=True)
    author = ReferenceField(Author, required=True)
    tags = ListField(StringField())

# Usage
author = Author(name="Jane Doe")
await author.save()

book = Book(
    title="Python Mastery",
    author=author,
    tags=["programming", "python"]
)
await book.save()