Skip to content

BaseField class

edgy.core.db.fields.base.BaseField

BaseField(*, default=Undefined, server_default=Undefined, inherit=True, **kwargs)

Bases: FieldInfo

The base field for all Edgy data model fields.

PARAMETER DESCRIPTION
default

TYPE: Any DEFAULT: Undefined

server_default

TYPE: Any DEFAULT: Undefined

inherit

TYPE: bool DEFAULT: True

**kwargs

TYPE: Any DEFAULT: {}

Source code in edgy/core/db/fields/base.py
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
def __init__(
    self,
    *,
    default: Any = Undefined,
    server_default: Any = Undefined,
    inherit: bool = True,
    **kwargs: Any,
) -> None:
    self.max_digits: str = kwargs.pop("max_digits", None)
    self.decimal_places: str = kwargs.pop("decimal_places", None)
    self.server_default: Any = server_default
    self.read_only: bool = kwargs.pop("read_only", False)
    self.primary_key: bool = kwargs.pop("primary_key", False)
    self.autoincrement: bool = kwargs.pop("autoincrement", False)
    self.inherit = inherit

    super().__init__(**kwargs)

    self.null: bool = kwargs.pop("null", False)
    if self.null and default is Undefined:
        default = None
    if default is not Undefined:
        self.default = default
    if (default is not None and default is not Undefined) or (
        self.server_default is not None and self.server_default != Undefined
    ):
        self.null = True
    self.field_type: Any = kwargs.pop("__type__", None)
    self.__original_type__: type = kwargs.pop("__original_type__", None)
    self.column_type: Optional[Any] = kwargs.pop("column_type", None)
    self.constraints: Sequence[sqlalchemy.Constraint] = kwargs.pop("constraints", [])
    self.skip_absorption_check: bool = kwargs.pop("skip_absorption_check", False)
    self.help_text: Optional[str] = kwargs.pop("help_text", None)
    self.pattern: Pattern = kwargs.pop("pattern", None)
    self.unique: bool = kwargs.pop("unique", False)
    self.index: bool = kwargs.pop("index", False)
    self.choices: Sequence = kwargs.pop("choices", [])
    self.owner: Union[Type["Model"], Type["ReflectModel"]] = kwargs.pop("owner", None)
    # field name, set when retrieving
    self.name: str = kwargs.get("name", None)
    self.alias: str = kwargs.pop("name", None)
    self.regex: str = kwargs.pop("regex", None)
    self.format: str = kwargs.pop("format", None)
    self.min_length: Optional[int] = kwargs.pop("min_length", None)
    self.max_length: Optional[int] = kwargs.pop("max_length", None)
    self.minimum: Optional[Union[int, float, decimal.Decimal]] = kwargs.pop("minimum", None)
    self.maximum: Optional[Union[int, float, decimal.Decimal]] = kwargs.pop("maximum", None)
    self.multiple_of: Optional[Union[int, float, decimal.Decimal]] = kwargs.pop("multiple_of", None)
    self.server_onupdate: Any = kwargs.pop("server_onupdate", None)
    self.registry: Registry = kwargs.pop("registry", None)
    self.comment: str = kwargs.pop("comment", None)
    self.secret: bool = kwargs.pop("secret", False)


    # set remaining attributes
    for name, value in kwargs.items():
        setattr(self, name, value)

    if self.primary_key:
        self.field_type = Any
        self.null = True

    if isinstance(self.default, bool):
        self.null = True
    self.__namespace__ = {k: v for k, v in self.__dict__.items() if k != "__namespace__"}

max_digits instance-attribute

max_digits = pop('max_digits', None)

decimal_places instance-attribute

decimal_places = pop('decimal_places', None)

server_default instance-attribute

server_default = server_default

read_only instance-attribute

read_only = pop('read_only', False)

primary_key instance-attribute

primary_key = pop('primary_key', False)

autoincrement instance-attribute

autoincrement = pop('autoincrement', False)

inherit instance-attribute

inherit = inherit

null instance-attribute

null = pop('null', False)

default instance-attribute

default = default

field_type instance-attribute

field_type = pop('__type__', None)

__original_type__ instance-attribute

__original_type__ = pop('__original_type__', None)

column_type instance-attribute

column_type = pop('column_type', None)

constraints instance-attribute

constraints = pop('constraints', [])

skip_absorption_check instance-attribute

skip_absorption_check = pop('skip_absorption_check', False)

help_text instance-attribute

help_text = pop('help_text', None)

pattern instance-attribute

pattern = pop('pattern', None)

unique instance-attribute

unique = pop('unique', False)

index instance-attribute

index = pop('index', False)

choices instance-attribute

choices = pop('choices', [])

owner instance-attribute

owner = pop('owner', None)

name instance-attribute

name = get('name', None)

alias instance-attribute

alias = pop('name', None)

regex instance-attribute

regex = pop('regex', None)

format instance-attribute

format = pop('format', None)

min_length instance-attribute

min_length = pop('min_length', None)

max_length instance-attribute

max_length = pop('max_length', None)

minimum instance-attribute

minimum = pop('minimum', None)

maximum instance-attribute

maximum = pop('maximum', None)

multiple_of instance-attribute

multiple_of = pop('multiple_of', None)

server_onupdate instance-attribute

server_onupdate = pop('server_onupdate', None)

registry instance-attribute

registry = pop('registry', None)

comment instance-attribute

comment = pop('comment', None)

secret instance-attribute

secret = pop('secret', False)

__namespace__ class-attribute instance-attribute

__namespace__ = {k: _yfor (k, v) in items() if k != '__namespace__'}

namespace property

namespace

Returns the properties added to the fields in a dict format

is_required

is_required()

Check if the argument is required.

RETURNS DESCRIPTION
bool

True if the argument is required, False otherwise.

Source code in edgy/core/db/fields/base.py
116
117
118
119
120
121
122
123
124
125
def is_required(self) -> bool:
    """Check if the argument is required.

    Returns:
        `True` if the argument is required, `False` otherwise.
    """
    if self.primary_key:
        if self.autoincrement:
            return False
    return False if self.null or self.server_default else True

get_alias

get_alias()

Used to translate the model column names into database column tables.

Source code in edgy/core/db/fields/base.py
127
128
129
130
131
def get_alias(self) -> str:
    """
    Used to translate the model column names into database column tables.
    """
    return self.name

has_default

has_default()

Checks if the field has a default value set

Source code in edgy/core/db/fields/base.py
133
134
135
def has_default(self) -> bool:
    """Checks if the field has a default value set"""
    return bool(self.default is not None and self.default is not Undefined)

get_columns

get_columns(name)

Returns the columns of the field being declared.

PARAMETER DESCRIPTION
name

TYPE: str

Source code in edgy/core/db/fields/base.py
137
138
139
140
141
def get_columns(self, name: str) -> Sequence[sqlalchemy.Column]:
    """
    Returns the columns of the field being declared.
    """
    return []

get_column_names

get_column_names(name='')
PARAMETER DESCRIPTION
name

TYPE: str DEFAULT: ''

Source code in edgy/core/db/fields/base.py
143
144
145
146
def get_column_names(self, name: str="") -> FrozenSet[str]:
    if name:
        return self.owner.meta.field_to_column_names[name]
    return self.owner.meta.field_to_column_names[self.name]

clean

clean(field_name, value, for_query=False)

Validates a value and transform it into columns which can be used for querying and saving. for_query: is used for querying. Should have all columns used for querying set.

PARAMETER DESCRIPTION
field_name

TYPE: str

value

TYPE: Any

for_query

TYPE: bool DEFAULT: False

Source code in edgy/core/db/fields/base.py
148
149
150
151
152
153
def clean(self, field_name: str, value: Any, for_query: bool=False) -> Dict[str, Any]:
    """
    Validates a value and transform it into columns which can be used for querying and saving.
    for_query: is used for querying. Should have all columns used for querying set.
    """
    return {}

to_model

to_model(field_name, value, phase='')

Inverse of clean. Transforms column(s) to a field for a pydantic model (EdgyBaseModel). Validation happens later.

PARAMETER DESCRIPTION
field_name

TYPE: str

value

TYPE: Any

phase

TYPE: str DEFAULT: ''

Source code in edgy/core/db/fields/base.py
155
156
157
158
159
160
def to_model(self, field_name: str, value: Any, phase: str = "") -> Dict[str, Any]:
    """
    Inverse of clean. Transforms column(s) to a field for a pydantic model (EdgyBaseModel).
    Validation happens later.
    """
    return {field_name: value}

get_embedded_fields

get_embedded_fields(field_name, fields_mapping)

Define extra fields on the fly. Often no owner is available yet.

Arguments are: name: the field name fields_mapping: the existing fields

PARAMETER DESCRIPTION
field_name

TYPE: str

fields_mapping

TYPE: Dict[str, BaseField]

the returned fields are changed after return, so you should

return new fields or copies. Also set the owner of the field to them before returning

Source code in edgy/core/db/fields/base.py
162
163
164
165
166
167
168
169
170
171
172
173
def get_embedded_fields(self, field_name: str, fields_mapping: Dict[str, "BaseField"]) -> Dict[str, "BaseField"]:
    """
    Define extra fields on the fly. Often no owner is available yet.

    Arguments are:
    name: the field name
    fields_mapping: the existing fields

    Note: the returned fields are changed after return, so you should
          return new fields or copies. Also set the owner of the field to them before returning
    """
    return {}

embed_field

embed_field(prefix, new_fieldname, owner=None, parent=None)

Embed this field or return None to prevent embedding. Must return a copy with name and owner set when not returning None.

PARAMETER DESCRIPTION
prefix

TYPE: str

new_fieldname

TYPE: str

owner

TYPE: Optional[Union[Type[Model], Type[ReflectModel]]] DEFAULT: None

parent

TYPE: Optional[BaseField] DEFAULT: None

Source code in edgy/core/db/fields/base.py
175
176
177
178
179
180
181
182
183
def embed_field(self, prefix: str, new_fieldname:str, owner: Optional[Union[Type["Model"], Type["ReflectModel"]]]=None, parent: Optional["BaseField"]=None) -> Optional["BaseField"]:
    """
    Embed this field or return None to prevent embedding.
    Must return a copy with name and owner set when not returning None.
    """
    field_copy = copy.copy(self)
    field_copy.name = new_fieldname
    field_copy.owner = owner  # type: ignore
    return field_copy

get_constraints

get_constraints()
Source code in edgy/core/db/fields/base.py
185
186
def get_constraints(self) -> Any:
    return self.constraints

get_global_constraints

get_global_constraints(name, columns)

Return global constraints and indexes. Useful for multicolumn fields

PARAMETER DESCRIPTION
name

TYPE: str

columns

TYPE: Sequence[Column]

Source code in edgy/core/db/fields/base.py
188
189
190
191
192
def get_global_constraints(self, name: str, columns: Sequence[sqlalchemy.Column]) -> Sequence[sqlalchemy.Constraint]:
    """Return global constraints and indexes.
    Useful for multicolumn fields
    """
    return []

get_default_value

get_default_value()
Source code in edgy/core/db/fields/base.py
194
195
196
197
198
199
def get_default_value(self) -> Any:
    # single default
    default = getattr(self, "default", None)
    if callable(default):
        return default()
    return default

get_default_values

get_default_values(field_name, cleaned_data)
PARAMETER DESCRIPTION
field_name

TYPE: str

cleaned_data

TYPE: Dict[str, Any]

Source code in edgy/core/db/fields/base.py
201
202
203
204
205
206
207
208
def get_default_values(self, field_name: str, cleaned_data: Dict[str, Any]) -> Any:
    # for multidefaults overwrite in subclasses get_default_values to
    # parse default values differently
    # NOTE: multi value fields should always check here if defaults were already applied
    # NOTE: when build meta fields without columns this should be empty
    if field_name in cleaned_data:
        return {}
    return {field_name: self.get_default_value()}