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:
objectBase 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:
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:
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:
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:
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:
Examples
>>> field = Field() >>> field.cast_to_surreal_type() '<any>'
- class surrealengine.fields.id.RecordIDField(table_name=None, **kwargs)[source]¶
Bases:
FieldRecordID 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()
- 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
Scalar Fields¶
- class surrealengine.fields.scalar.StringField(min_length=None, max_length=None, regex=None, choices=None, **kwargs)[source]¶
Bases:
FieldString 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:
NumberFieldInteger 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
- class surrealengine.fields.scalar.FloatField(**kwargs)[source]¶
Bases:
NumberFieldFloat 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
- class surrealengine.fields.scalar.NumberField(min_value=None, max_value=None, **kwargs)[source]¶
Bases:
FieldBase 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:
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:
- class surrealengine.fields.scalar.BooleanField(**kwargs)[source]¶
Bases:
FieldBoolean 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
- class surrealengine.fields.specialized.DecimalField(**kwargs)[source]¶
Bases:
NumberFieldDecimal 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.
Collection Fields¶
- class surrealengine.fields.collection.ListField(field_type=None, max_items=None, surreal_functions=None, **kwargs)[source]¶
Bases:
FieldList 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:
- 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.
- class surrealengine.fields.collection.DictField(field_type=None, schema=None, **kwargs)[source]¶
Bases:
FieldDict 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
- 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:
- 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.
- class surrealengine.fields.collection.SetField(field_type=None, max_items=None, surreal_functions=None, **kwargs)[source]¶
Bases:
ListFieldSet 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())
DateTime Fields¶
- class surrealengine.fields.datetime.DateTimeField(**kwargs)[source]¶
Bases:
FieldDateTime 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
dprefix 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.
- class surrealengine.fields.datetime.DurationField(**kwargs)[source]¶
Bases:
FieldDuration 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.
- class surrealengine.fields.datetime.TimeSeriesField(**kwargs)[source]¶
Bases:
DateTimeFieldField 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”
Reference Fields¶
- class surrealengine.fields.reference.ReferenceField(document_type, **kwargs)[source]¶
Bases:
FieldReference 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:
- 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.
- class surrealengine.fields.reference.RelationField(to_document, **kwargs)[source]¶
Bases:
FieldField 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.
- 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.
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:
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:
Specialized Fields¶
- class surrealengine.fields.specialized.EmailField(**kwargs)[source]¶
Bases:
StringFieldEmail 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:
StringFieldEnhanced 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:
- 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
- class surrealengine.fields.specialized.IPAddressField(ipv4_only=False, ipv6_only=False, version=None, **kwargs)[source]¶
Bases:
StringFieldIP 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.
- 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:
StringFieldSlug 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:
FieldChoice 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'])
- 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:
FieldField 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.
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:
- Raises:
ValidationError – If the geometry data is invalid or improperly formatted.
Additional Fields¶
- class surrealengine.fields.additional.OptionField(field_type, **kwargs)[source]¶
Bases:
FieldOption 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
- 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:
- 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.
- class surrealengine.fields.specialized.LiteralField(allowed_values, **kwargs)[source]¶
Bases:
FieldField 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()])
- 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:
- 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.
- class surrealengine.fields.additional.RangeField(min_type, max_type=None, **kwargs)[source]¶
Bases:
FieldField 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())
- 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:
- class surrealengine.fields.additional.FutureField(computation_expression, **kwargs)[source]¶
Bases:
FieldField 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
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()