blissoda.xrpd.models.XrpdPlotInfo#
- class blissoda.xrpd.models.XrpdPlotInfo(*args, pk: str | None = None, scan_name: str, lima_name: str, radial_label: str, azim_label: str | None, hdf5_url: str | None, timestamp: datetime, field_names: List[Literal['radial', 'azimuthal', 'intensity']], color: str | None = None, is_last_scan: bool = True, is_sum: bool = False, **kwargs)[source]#
Bases:
JsonModel- class ConfigDict#
Bases:
TypedDictA TypedDict for configuring Pydantic behaviour.
- alias_generator: Callable[[str], str] | AliasGenerator | None#
A callable that takes a field name and returns an alias for it or an instance of [AliasGenerator][pydantic.aliases.AliasGenerator]. Defaults to None.
When using a callable, the alias generator is used for both validation and serialization. If you want to use different alias generators for validation and serialization, you can use [AliasGenerator][pydantic.aliases.AliasGenerator] instead.
If data source field names do not match your code style (e.g. CamelCase fields), you can automatically generate aliases using alias_generator. Here’s an example with a basic callable:
```python from pydantic import BaseModel, ConfigDict from pydantic.alias_generators import to_pascal
- class Voice(BaseModel):
model_config = ConfigDict(alias_generator=to_pascal)
name: str language_code: str
voice = Voice(Name=’Filiz’, LanguageCode=’tr-TR’) print(voice.language_code) #> tr-TR print(voice.model_dump(by_alias=True)) #> {‘Name’: ‘Filiz’, ‘LanguageCode’: ‘tr-TR’} ```
If you want to use different alias generators for validation and serialization, you can use [AliasGenerator][pydantic.aliases.AliasGenerator].
```python from pydantic import AliasGenerator, BaseModel, ConfigDict from pydantic.alias_generators import to_camel, to_pascal
- class Athlete(BaseModel):
first_name: str last_name: str sport: str
- model_config = ConfigDict(
- alias_generator=AliasGenerator(
validation_alias=to_camel, serialization_alias=to_pascal,
)
)
athlete = Athlete(firstName=’John’, lastName=’Doe’, sport=’track’) print(athlete.model_dump(by_alias=True)) #> {‘FirstName’: ‘John’, ‘LastName’: ‘Doe’, ‘Sport’: ‘track’} ```
- Note:
Pydantic offers three built-in alias generators: [to_pascal][pydantic.alias_generators.to_pascal], [to_camel][pydantic.alias_generators.to_camel], and [to_snake][pydantic.alias_generators.to_snake].
- allow_inf_nan: bool#
Whether to allow infinity (+inf an -inf) and NaN values to float and decimal fields. Defaults to True.
- arbitrary_types_allowed: bool#
Whether arbitrary types are allowed for field types. Defaults to False.
```python from pydantic import BaseModel, ConfigDict, ValidationError
# This is not a pydantic model, it’s an arbitrary class class Pet:
- def __init__(self, name: str):
self.name = name
- class Model(BaseModel):
model_config = ConfigDict(arbitrary_types_allowed=True)
pet: Pet owner: str
pet = Pet(name=’Hedwig’) # A simple check of instance type is used to validate the data model = Model(owner=’Harry’, pet=pet) print(model) #> pet=<__main__.Pet object at 0x0123456789ab> owner=’Harry’ print(model.pet) #> <__main__.Pet object at 0x0123456789ab> print(model.pet.name) #> Hedwig print(type(model.pet)) #> <class ‘__main__.Pet’> try:
# If the value is not an instance of the type, it’s invalid Model(owner=’Harry’, pet=’Hedwig’)
- except ValidationError as e:
print(e) ‘’’ 1 validation error for Model pet
Input should be an instance of Pet [type=is_instance_of, input_value=’Hedwig’, input_type=str]
‘’’
# Nothing in the instance of the arbitrary type is checked # Here name probably should have been a str, but it’s not validated pet2 = Pet(name=42) model2 = Model(owner=’Harry’, pet=pet2) print(model2) #> pet=<__main__.Pet object at 0x0123456789ab> owner=’Harry’ print(model2.pet) #> <__main__.Pet object at 0x0123456789ab> print(model2.pet.name) #> 42 print(type(model2.pet)) #> <class ‘__main__.Pet’> ```
- cache_strings: bool | Literal['all', 'keys', 'none']#
Whether to cache strings to avoid constructing new Python objects. Defaults to True.
Enabling this setting should significantly improve validation performance while increasing memory usage slightly.
True or ‘all’ (the default): cache all strings
‘keys’: cache only dictionary keys
False or ‘none’: no caching
- !!! note
True or ‘all’ is required to cache strings during general validation because validators don’t know if they’re in a key or a value.
- !!! tip
If repeated strings are rare, it’s recommended to use ‘keys’ or ‘none’ to reduce memory usage, as the performance difference is minimal if repeated strings are rare.
/// version-added | v2.7 ///
- clear() None. Remove all items from D.#
- coerce_numbers_to_str: bool#
If True, enables automatic coercion of any Number type to str in “lax” (non-strict) mode. Defaults to False.
Pydantic doesn’t allow number types (int, float, Decimal) to be coerced as type str by default.
```python from decimal import Decimal
from pydantic import BaseModel, ConfigDict, ValidationError
- class Model(BaseModel):
value: str
- try:
print(Model(value=42))
- except ValidationError as e:
print(e) ‘’’ 1 validation error for Model value
Input should be a valid string [type=string_type, input_value=42, input_type=int]
‘’’
- class Model(BaseModel):
model_config = ConfigDict(coerce_numbers_to_str=True)
value: str
repr(Model(value=42).value) #> “42” repr(Model(value=42.13).value) #> “42.13” repr(Model(value=Decimal(‘42.13’)).value) #> “42.13” ```
- copy() a shallow copy of D#
- defer_build: bool#
Whether to defer model validator and serializer construction until the first model validation. Defaults to False.
This can be useful to avoid the overhead of building models which are only used nested within other models, or when you want to manually define type namespace via [Model.model_rebuild(_types_namespace=…)][pydantic.BaseModel.model_rebuild].
/// version-changed | v2.10 The setting also applies to [Pydantic dataclasses](../concepts/dataclasses.md) and [type adapters](../concepts/type_adapter.md). ///
- extra: ExtraValues | None#
Whether to ignore, allow, or forbid extra data during model initialization. Defaults to ‘ignore’.
Three configuration values are available:
‘ignore’: Providing extra data is ignored (the default): ```python from pydantic import BaseModel, ConfigDict
- class User(BaseModel):
model_config = ConfigDict(extra=’ignore’) # (1)!
name: str
user = User(name=’John Doe’, age=20) # (2)! print(user) #> name=’John Doe’ ```
This is the default behaviour.
The age argument is ignored.
‘forbid’: Providing extra data is not permitted, and a [ValidationError][pydantic_core.ValidationError] will be raised if this is the case: ```python from pydantic import BaseModel, ConfigDict, ValidationError
- class Model(BaseModel):
x: int
model_config = ConfigDict(extra=’forbid’)
- try:
Model(x=1, y=’a’)
- except ValidationError as exc:
print(exc) “”” 1 validation error for Model y
Extra inputs are not permitted [type=extra_forbidden, input_value=’a’, input_type=str]
“””
‘allow’: Providing extra data is allowed and stored in the __pydantic_extra__ dictionary attribute: ```python from pydantic import BaseModel, ConfigDict
- class Model(BaseModel):
x: int
model_config = ConfigDict(extra=’allow’)
m = Model(x=1, y=’a’) assert m.__pydantic_extra__ == {‘y’: ‘a’} ``` By default, no validation will be applied to these extra items, but you can set a type for the values by overriding the type annotation for __pydantic_extra__: ```python from pydantic import BaseModel, ConfigDict, Field, ValidationError
- class Model(BaseModel):
__pydantic_extra__: dict[str, int] = Field(init=False) # (1)!
x: int
model_config = ConfigDict(extra=’allow’)
- try:
Model(x=1, y=’a’)
- except ValidationError as exc:
print(exc) “”” 1 validation error for Model y
Input should be a valid integer, unable to parse string as an integer [type=int_parsing, input_value=’a’, input_type=str]
“””
m = Model(x=1, y=’2’) assert m.x == 1 assert m.y == 2 assert m.model_dump() == {‘x’: 1, ‘y’: 2} assert m.__pydantic_extra__ == {‘y’: 2} ```
The = Field(init=False) does not have any effect at runtime, but prevents the __pydantic_extra__ field from being included as a parameter to the model’s __init__ method by type checkers.
As well as specifying an extra configuration value on the model, you can also provide it as an argument to the validation methods. This will override any extra configuration value set on the model: ```python from pydantic import BaseModel, ConfigDict, ValidationError
- class Model(BaseModel):
x: int model_config = ConfigDict(extra=”allow”)
- try:
# Override model config and forbid extra fields just this time Model.model_validate({“x”: 1, “y”: 2}, extra=”forbid”)
- except ValidationError as exc:
print(exc) “”” 1 validation error for Model y
Extra inputs are not permitted [type=extra_forbidden, input_value=2, input_type=int]
“””
- field_title_generator: Callable[[str, FieldInfo | ComputedFieldInfo], str] | None#
A callable that takes a field’s name and info and returns title for it. Defaults to None.
- from_attributes: bool#
Whether to build models and look up discriminators of tagged unions using python object attributes.
- fromkeys(value=None, /)#
Create a new dictionary with keys from iterable and values set to value.
- frozen: bool#
Whether models are faux-immutable, i.e. whether __setattr__ is allowed, and also generates a __hash__() method for the model. This makes instances of the model potentially hashable if all the attributes are hashable. Defaults to False.
- Note:
On V1, the inverse of this setting was called allow_mutation, and was True by default.
- get(key, default=None, /)#
Return the value for key if key is in the dictionary, else default.
- hide_input_in_errors: bool#
Whether to hide inputs when printing errors. Defaults to False.
Pydantic shows the input value and type when it raises ValidationError during the validation.
```python from pydantic import BaseModel, ValidationError
- class Model(BaseModel):
a: str
- try:
Model(a=123)
- except ValidationError as e:
print(e) ‘’’ 1 validation error for Model a
Input should be a valid string [type=string_type, input_value=123, input_type=int]
‘’’
You can hide the input value and type by setting the hide_input_in_errors config to True.
```python from pydantic import BaseModel, ConfigDict, ValidationError
- class Model(BaseModel):
a: str model_config = ConfigDict(hide_input_in_errors=True)
- try:
Model(a=123)
- except ValidationError as e:
print(e) ‘’’ 1 validation error for Model a
Input should be a valid string [type=string_type]
‘’’
- ignored_types: tuple[type, ...]#
A tuple of types that may occur as values of class attributes without annotations. This is typically used for custom descriptors (classes that behave like property). If an attribute is set on a class without an annotation and has a type that is not in this tuple (or otherwise recognized by _pydantic_), an error will be raised. Defaults to ().
- items() a set-like object providing a view on D's items#
- json_encoders: dict[type[object], JsonEncoder] | None#
A dict of custom JSON encoders for specific types. Defaults to None.
/// version-deprecated | v2 This configuration option is a carryover from v1. We originally planned to remove it in v2 but didn’t have a 1:1 replacement so we are keeping it for now. It is still deprecated and will likely be removed in the future. ///
- json_schema_extra: JsonDict | JsonSchemaExtraCallable | None#
A dict or callable to provide extra JSON schema properties. Defaults to None.
- json_schema_mode_override: Literal['validation', 'serialization', None]#
If not None, the specified mode will be used to generate the JSON schema regardless of what mode was passed to the function call. Defaults to None.
This provides a way to force the JSON schema generation to reflect a specific mode, e.g., to always use the validation schema.
It can be useful when using frameworks (such as FastAPI) that may generate different schemas for validation and serialization that must both be referenced from the same schema; when this happens, we automatically append -Input to the definition reference for the validation schema and -Output to the definition reference for the serialization schema. By specifying a json_schema_mode_override though, this prevents the conflict between the validation and serialization schemas (since both will use the specified schema), and so prevents the suffixes from being added to the definition references.
```python from pydantic import BaseModel, ConfigDict, Json
- class Model(BaseModel):
a: Json[int] # requires a string to validate, but will dump an int
print(Model.model_json_schema(mode=’serialization’)) ‘’’ {
‘properties’: {‘a’: {‘title’: ‘A’, ‘type’: ‘integer’}}, ‘required’: [‘a’], ‘title’: ‘Model’, ‘type’: ‘object’,
}#
- class ForceInputModel(Model):
# the following ensures that even with mode=’serialization’, we # will get the schema that would be generated for validation. model_config = ConfigDict(json_schema_mode_override=’validation’)
print(ForceInputModel.model_json_schema(mode=’serialization’)) ‘’’ {
- ‘properties’: {
- ‘a’: {
‘contentMediaType’: ‘application/json’, ‘contentSchema’: {‘type’: ‘integer’}, ‘title’: ‘A’, ‘type’: ‘string’,
}
}, ‘required’: [‘a’], ‘title’: ‘ForceInputModel’, ‘type’: ‘object’,
}#
/// version-added | v2.4 ///
- json_schema_serialization_defaults_required: bool#
Whether fields with default values should be marked as required in the serialization schema. Defaults to False.
This ensures that the serialization schema will reflect the fact a field with a default will always be present when serializing the model, even though it is not required for validation.
However, there are scenarios where this may be undesirable — in particular, if you want to share the schema between validation and serialization, and don’t mind fields with defaults being marked as not required during serialization. See [#7209](pydantic/pydantic#7209) for more details.
```python from pydantic import BaseModel, ConfigDict
- class Model(BaseModel):
a: str = ‘a’
model_config = ConfigDict(json_schema_serialization_defaults_required=True)
print(Model.model_json_schema(mode=’validation’)) ‘’’ {
‘properties’: {‘a’: {‘default’: ‘a’, ‘title’: ‘A’, ‘type’: ‘string’}}, ‘title’: ‘Model’, ‘type’: ‘object’,
}#
print(Model.model_json_schema(mode=’serialization’)) ‘’’ {
‘properties’: {‘a’: {‘default’: ‘a’, ‘title’: ‘A’, ‘type’: ‘string’}}, ‘required’: [‘a’], ‘title’: ‘Model’, ‘type’: ‘object’,
}#
/// version-added | v2.4 ///
- keys() a set-like object providing a view on D's keys#
- loc_by_alias: bool#
Whether to use the actual key provided in the data (e.g. alias) for error loc`s rather than the field’s name. Defaults to `True.
- model_title_generator: Callable[[type], str] | None#
A callable that takes a model class and returns the title for it. Defaults to None.
- plugin_settings: dict[str, object] | None#
A dict of settings for plugins. Defaults to None.
- polymorphic_serialization: bool#
Whether to use polymorphic serialization for subclasses of the model or Pydantic dataclass. Defaults to False.
- pop(k[, d]) v, remove specified key and return the corresponding value.#
If key is not found, default is returned if given, otherwise KeyError is raised
- popitem()#
Remove and return a (key, value) pair as a 2-tuple.
Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.
- populate_by_name: bool#
Whether an aliased field may be populated by its name as given by the model attribute, as well as the alias. Defaults to False.
- !!! warning
populate_by_name usage is not recommended in v2.11+ and will be deprecated in v3. Instead, you should use the [validate_by_name][pydantic.config.ConfigDict.validate_by_name] configuration setting.
When validate_by_name=True and validate_by_alias=True, this is strictly equivalent to the previous behavior of populate_by_name=True.
In v2.11, we also introduced a [validate_by_alias][pydantic.config.ConfigDict.validate_by_alias] setting that introduces more fine grained control for validation behavior.
Here’s how you might go about using the new settings to achieve the same behavior:
```python from pydantic import BaseModel, ConfigDict, Field
- class Model(BaseModel):
model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)
my_field: str = Field(alias=’my_alias’) # (1)!
m = Model(my_alias=’foo’) # (2)! print(m) #> my_field=’foo’
m = Model(my_field=’foo’) # (3)! print(m) #> my_field=’foo’ ```
The field ‘my_field’ has an alias ‘my_alias’.
The model is populated by the alias ‘my_alias’.
The model is populated by the attribute name ‘my_field’.
- protected_namespaces: tuple[str | Pattern[str], ...]#
A tuple of strings and/or regex patterns that prevent models from having fields with names that conflict with its existing members/methods.
Strings are matched on a prefix basis. For instance, with ‘dog’, having a field named ‘dog_name’ will be disallowed.
Regex patterns are matched on the entire field name. For instance, with the pattern ‘^dog$’, having a field named ‘dog’ will be disallowed, but ‘dog_name’ will be accepted.
Defaults to (‘model_validate’, ‘model_dump’). This default is used to prevent collisions with the existing (and possibly future) [validation](../concepts/models.md#validating-data) and [serialization](../concepts/serialization.md#serializing-data) methods.
from pydantic import BaseModel
warnings.filterwarnings(‘error’) # Raise warnings as errors
try:
- class Model(BaseModel):
model_dump_something: str
- except UserWarning as e:
print(e) ‘’’ Field ‘model_dump_something’ in ‘Model’ conflicts with protected namespace ‘model_dump’.
You may be able to solve this by setting the ‘protected_namespaces’ configuration to (‘model_validate’,). ‘’’
You can customize this behavior using the protected_namespaces setting:
```python {test=”skip”} import re import warnings
from pydantic import BaseModel, ConfigDict
- with warnings.catch_warnings(record=True) as caught_warnings:
warnings.simplefilter(‘always’) # Catch all warnings
- class Model(BaseModel):
safe_field: str also_protect_field: str protect_this: str
- model_config = ConfigDict(
- protected_namespaces=(
‘protect_me_’, ‘also_protect_’, re.compile(‘^protect_this$’),
)
)
- for warning in caught_warnings:
print(f’{warning.message}’) ‘’’ Field ‘also_protect_field’ in ‘Model’ conflicts with protected namespace ‘also_protect_’. You may be able to solve this by setting the ‘protected_namespaces’ configuration to (’protect_me_’, re.compile(‘^protect_this$’))`.
Field ‘protect_this’ in ‘Model’ conflicts with protected namespace ‘re.compile(‘^protect_this$’)’. You may be able to solve this by setting the ‘protected_namespaces’ configuration to (’protect_me_’, ‘also_protect_’)`. ‘’’
While Pydantic will only emit a warning when an item is in a protected namespace but does not actually have a collision, an error _is_ raised if there is an actual collision with an existing attribute:
```python from pydantic import BaseModel, ConfigDict
try:
- class Model(BaseModel):
model_validate: str
model_config = ConfigDict(protected_namespaces=(’model_’,))
- except ValueError as e:
print(e) ‘’’ Field ‘model_validate’ conflicts with member <bound method BaseModel.model_validate of <class ‘pydantic.main.BaseModel’>> of protected namespace ‘model_’. ‘’’
/// version-changed | v2.10 The default protected namespaces was changed from (‘model_’,) to (‘model_validate’, ‘model_dump’), to allow for fields like model_id, model_name to be used. ///
- regex_engine: Literal['rust-regex', 'python-re']#
The regex engine to be used for pattern validation. Defaults to ‘rust-regex’.
‘rust-regex’ uses the [regex](https://docs.rs/regex) Rust crate, which is non-backtracking and therefore more DDoS resistant, but does not support all regex features.
‘python-re’ use the [re][] module, which supports all regex features, but may be slower.
- !!! note
If you use a compiled regex pattern, the ‘python-re’ engine will be used regardless of this setting. This is so that flags such as [re.IGNORECASE][] are respected.
```python from pydantic import BaseModel, ConfigDict, Field, ValidationError
- class Model(BaseModel):
model_config = ConfigDict(regex_engine=’python-re’)
value: str = Field(pattern=r’^abc(?=def)’)
print(Model(value=’abcdef’).value) #> abcdef
- try:
print(Model(value=’abxyzcdef’))
- except ValidationError as e:
print(e) ‘’’ 1 validation error for Model value
String should match pattern ‘^abc(?=def)’ [type=string_pattern_mismatch, input_value=’abxyzcdef’, input_type=str]
‘’’
/// version-added | v2.5 ///
- revalidate_instances: Literal['always', 'never', 'subclass-instances']#
When and how to revalidate models and dataclasses during validation. Can be one of:
‘never’: will not revalidate models and dataclasses during validation
‘always’: will revalidate models and dataclasses during validation
- ‘subclass-instances’: will revalidate models and dataclasses during validation if the instance is a
subclass of the model or dataclass
The default is ‘never’ (no revalidation).
This configuration only affects the current model it is applied on, and does not propagate to the models referenced in fields.
```python from pydantic import BaseModel
- class User(BaseModel, revalidate_instances=’never’): # (1)!
name: str
- class Transaction(BaseModel):
user: User
my_user = User(name=’John’) t = Transaction(user=my_user)
my_user.name = 1 # (2)! t = Transaction(user=my_user) # (3)! print(t) #> user=User(name=1) ```
This is the default behavior.
The assignment is not validated, unless you set [validate_assignment][pydantic.ConfigDict.validate_assignment] in the configuration.
Since revalidate_instances is set to ‘never’, the user instance is not revalidated.
Here is an example demonstrating the behavior of ‘subclass-instances’:
```python from pydantic import BaseModel
- class User(BaseModel, revalidate_instances=’subclass-instances’):
name: str
- class SubUser(User):
age: int
- class Transaction(BaseModel):
user: User
my_user = User(name=’John’) my_user.name = 1 # (1)! t = Transaction(user=my_user) # (2)! print(t) #> user=User(name=1)
my_sub_user = SubUser(name=’John’, age=20) t = Transaction(user=my_sub_user) print(t) # (3)! #> user=User(name=’John’) ```
The assignment is not validated, unless you set [validate_assignment][pydantic.ConfigDict.validate_assignment] in the configuration.
Because my_user is a “direct” instance of User, it is not being revalidated. It would have been the case if
revalidate_instances was set to ‘always’.
Because my_sub_user is an instance of a User subclass, it is being revalidated. In this case, Pydantic coerces my_sub_user to the defined User class defined on Transaction. If one of its fields had an invalid value, a validation error would have been raised.
/// version-added | v2 ///
- schema_generator: type[_GenerateSchema] | None#
The GenerateSchema class to use during core schema generation.
/// version-deprecated | v2.10 The GenerateSchema class is private and highly subject to change. ///
- ser_json_bytes: Literal['utf8', 'base64', 'hex']#
The encoding of JSON serialized bytes. Defaults to ‘utf8’. Set equal to val_json_bytes to get back an equal value after serialization round trip.
‘utf8’ will serialize bytes to UTF-8 strings.
‘base64’ will serialize bytes to URL safe base64 strings.
‘hex’ will serialize bytes to hexadecimal strings.
- ser_json_inf_nan: Literal['null', 'constants', 'strings']#
The encoding of JSON serialized infinity and NaN float values. Defaults to ‘null’.
‘null’ will serialize infinity and NaN values as null.
‘constants’ will serialize infinity and NaN values as Infinity and NaN.
‘strings’ will serialize infinity as string “Infinity” and NaN as string “NaN”.
- ser_json_temporal: Literal['iso8601', 'seconds', 'milliseconds']#
The format of JSON serialized temporal types from the [datetime][] module. This includes:
[datetime.datetime][]
[datetime.date][]
[datetime.time][]
[datetime.timedelta][]
Can be one of:
‘iso8601’ will serialize date-like types to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations).
‘milliseconds’ will serialize date-like types to a floating point number of milliseconds since the epoch.
‘seconds’ will serialize date-like types to a floating point number of seconds since the epoch.
Defaults to ‘iso8601’.
/// version-added | v2.12 This setting replaces [ser_json_timedelta][pydantic.config.ConfigDict.ser_json_timedelta], which will be deprecated in v3. ser_json_temporal adds more configurability for the other temporal types. ///
- ser_json_timedelta: Literal['iso8601', 'float']#
The format of JSON serialized timedeltas. Accepts the string values of ‘iso8601’ and ‘float’. Defaults to ‘iso8601’.
‘iso8601’ will serialize timedeltas to [ISO 8601 text format](https://en.wikipedia.org/wiki/ISO_8601#Durations).
‘float’ will serialize timedeltas to the total number of seconds.
/// version-changed | v2.12 It is now recommended to use the [ser_json_temporal][pydantic.config.ConfigDict.ser_json_temporal] setting. ser_json_timedelta will be deprecated in v3. ///
- serialize_by_alias: bool#
Whether an aliased field should be serialized by its alias. Defaults to False.
Note: In v2.11, serialize_by_alias was introduced to address the [popular request](pydantic/pydantic#8379) for consistency with alias behavior for validation and serialization settings. In v3, the default value is expected to change to True for consistency with the validation default.
```python from pydantic import BaseModel, ConfigDict, Field
- class Model(BaseModel):
model_config = ConfigDict(serialize_by_alias=True)
my_field: str = Field(serialization_alias=’my_alias’) # (1)!
m = Model(my_field=’foo’) print(m.model_dump()) # (2)! #> {‘my_alias’: ‘foo’} ```
The field ‘my_field’ has an alias ‘my_alias’.
The model is serialized using the alias ‘my_alias’ for the ‘my_field’ attribute.
/// version-added | v2.11 This setting was introduced to address the [popular request](pydantic/pydantic#8379) for consistency with alias behavior for validation and serialization.
In v3, the default value is expected to change to True for consistency with the validation default. ///
- setdefault(key, default=None, /)#
Insert key with a value of default if key is not in the dictionary.
Return the value for key if key is in the dictionary, else default.
- str_max_length: int | None#
The maximum length for str types. Defaults to None.
- str_min_length: int#
The minimum length for str types. Defaults to None.
- str_strip_whitespace: bool#
Whether to strip leading and trailing whitespace for str types.
- str_to_lower: bool#
Whether to convert all characters to lowercase for str types. Defaults to False.
- str_to_upper: bool#
Whether to convert all characters to uppercase for str types. Defaults to False.
- strict: bool#
Whether strict validation is applied to all fields on the model.
By default, Pydantic attempts to coerce values to the correct type, when possible.
There are situations in which you may want to disable this behavior, and instead raise an error if a value’s type does not match the field’s type annotation.
To configure strict mode for all fields on a model, you can set strict=True on the model.
```python from pydantic import BaseModel, ConfigDict
- class Model(BaseModel):
model_config = ConfigDict(strict=True)
name: str age: int
See [Strict Mode](../concepts/strict_mode.md) for more details.
See the [Conversion Table](../concepts/conversion_table.md) for more details on how Pydantic converts data in both strict and lax modes.
/// version-added | v2 ///
- title: str | None#
The title for the generated JSON schema, defaults to the model’s name
- update([E, ]**F) None. Update D from dict/iterable E and F.#
If E is present and has a .keys() method, then does: for k in E: D[k] = E[k] If E is present and lacks a .keys() method, then does: for k, v in E: D[k] = v In either case, this is followed by: for k in F: D[k] = F[k]
- url_preserve_empty_path: bool#
Whether to preserve empty URL paths when validating values for a URL type. Defaults to False.
```python from pydantic import AnyUrl, BaseModel, ConfigDict
- class Model(BaseModel):
model_config = ConfigDict(url_preserve_empty_path=True)
url: AnyUrl
m = Model(url=’http://example.com’) print(m.url) #> http://example.com ```
/// version-added | v2.12 ///
- use_attribute_docstrings: bool#
Whether docstrings of attributes (bare string literals immediately following the attribute declaration) should be used for field descriptions. Defaults to False.
```python from pydantic import BaseModel, ConfigDict, Field
- class Model(BaseModel):
model_config = ConfigDict(use_attribute_docstrings=True)
x: str “”” Example of an attribute docstring “””
y: int = Field(description=”Description in Field”) “”” Description in Field overrides attribute docstring “””
print(Model.model_fields[“x”].description) # > Example of an attribute docstring print(Model.model_fields[“y”].description) # > Description in Field ``` This requires the source code of the class to be available at runtime (and so won’t work in the interactive interpreter shell).
- !!! warning “Usage with TypedDict and stdlib dataclasses”
Due to current limitations, attribute docstrings detection may not work as expected when using [TypedDict][typing.TypedDict] and stdlib dataclasses, in particular when:
inheritance is being used.
multiple classes have the same name in the same source file (unless Python 3.13 or greater is used).
/// version-added | v2.7 ///
- use_enum_values: bool#
Whether to populate models with the value property of enums, rather than the raw enum. This may be useful if you want to serialize model.model_dump() later. Defaults to False.
- !!! note
If you have an Optional[Enum] value that you set a default for, you need to use validate_default=True for said Field to ensure that the use_enum_values flag takes effect on the default, as extracting an enum’s value occurs during validation, not serialization.
```python from enum import Enum from typing import Optional
from pydantic import BaseModel, ConfigDict, Field
- class SomeEnum(Enum):
FOO = ‘foo’ BAR = ‘bar’ BAZ = ‘baz’
- class SomeModel(BaseModel):
model_config = ConfigDict(use_enum_values=True)
some_enum: SomeEnum another_enum: Optional[SomeEnum] = Field(
default=SomeEnum.FOO, validate_default=True
)
model1 = SomeModel(some_enum=SomeEnum.BAR) print(model1.model_dump()) #> {‘some_enum’: ‘bar’, ‘another_enum’: ‘foo’}
model2 = SomeModel(some_enum=SomeEnum.BAR, another_enum=SomeEnum.BAZ) print(model2.model_dump()) #> {‘some_enum’: ‘bar’, ‘another_enum’: ‘baz’} ```
- val_json_bytes: Literal['utf8', 'base64', 'hex']#
/// version-added | v2.9 ///
The encoding of JSON serialized bytes to decode. Defaults to ‘utf8’. Set equal to ser_json_bytes to get back an equal value after serialization round trip.
‘utf8’ will deserialize UTF-8 strings to bytes.
‘base64’ will deserialize URL safe base64 strings to bytes.
‘hex’ will deserialize hexadecimal strings to bytes.
- val_temporal_unit: Literal['seconds', 'milliseconds', 'infer']#
The unit to assume for validating numeric input for datetime-like types ([datetime.datetime][] and [datetime.date][]). Can be one of:
‘seconds’ will validate date or time numeric inputs as seconds since the [epoch].
‘milliseconds’ will validate date or time numeric inputs as milliseconds since the [epoch].
‘infer’ will infer the unit from the string numeric input on unix time as:
seconds since the [epoch] if $-2^{10} <= v <= 2^{10}$
milliseconds since the [epoch] (if $v < -2^{10}$ or $v > 2^{10}$).
Defaults to ‘infer’.
/// version-added | v2.12 ///
- validate_assignment: bool#
Whether to validate the data when the model is changed. Defaults to False.
The default behavior of Pydantic is to validate the data when the model is created.
In case the user changes the data after the model is created, the model is _not_ revalidated.
```python from pydantic import BaseModel
- class User(BaseModel):
name: str
user = User(name=’John Doe’) # (1)! print(user) #> name=’John Doe’ user.name = 123 # (1)! print(user) #> name=123 ```
The validation happens only when the model is created.
The validation does not happen when the data is changed.
In case you want to revalidate the model when the data is changed, you can use validate_assignment=True:
```python from pydantic import BaseModel, ValidationError
- class User(BaseModel, validate_assignment=True): # (1)!
name: str
user = User(name=’John Doe’) # (2)! print(user) #> name=’John Doe’ try:
user.name = 123 # (3)!
- except ValidationError as e:
print(e) ‘’’ 1 validation error for User name
Input should be a valid string [type=string_type, input_value=123, input_type=int]
‘’’
You can either use class keyword arguments, or model_config to set validate_assignment=True.
The validation happens when the model is created.
The validation _also_ happens when the data is changed.
- validate_by_alias: bool#
Whether an aliased field may be populated by its alias. Defaults to True.
Here’s an example of disabling validation by alias:
```py from pydantic import BaseModel, ConfigDict, Field
- class Model(BaseModel):
model_config = ConfigDict(validate_by_name=True, validate_by_alias=False)
my_field: str = Field(validation_alias=’my_alias’) # (1)!
m = Model(my_field=’foo’) # (2)! print(m) #> my_field=’foo’ ```
The field ‘my_field’ has an alias ‘my_alias’.
The model can only be populated by the attribute name ‘my_field’.
- !!! warning
You cannot set both validate_by_alias and validate_by_name to False. This would make it impossible to populate an attribute.
See [usage errors](../errors/usage_errors.md#validate-by-alias-and-name-false) for an example.
If you set validate_by_alias to False, under the hood, Pydantic dynamically sets validate_by_name to True to ensure that validation can still occur.
/// version-added | v2.11 This setting was introduced in conjunction with [validate_by_name][pydantic.ConfigDict.validate_by_name] to empower users with more fine grained validation control. ///
- validate_by_name: bool#
Whether an aliased field may be populated by its name as given by the model attribute. Defaults to False.
```python from pydantic import BaseModel, ConfigDict, Field
- class Model(BaseModel):
model_config = ConfigDict(validate_by_name=True, validate_by_alias=True)
my_field: str = Field(validation_alias=’my_alias’) # (1)!
m = Model(my_alias=’foo’) # (2)! print(m) #> my_field=’foo’
m = Model(my_field=’foo’) # (3)! print(m) #> my_field=’foo’ ```
The field ‘my_field’ has an alias ‘my_alias’.
The model is populated by the alias ‘my_alias’.
The model is populated by the attribute name ‘my_field’.
- !!! warning
You cannot set both validate_by_alias and validate_by_name to False. This would make it impossible to populate an attribute.
See [usage errors](../errors/usage_errors.md#validate-by-alias-and-name-false) for an example.
/// version-added | v2.11 This setting was introduced in conjunction with [validate_by_alias][pydantic.ConfigDict.validate_by_alias] to empower users with more fine grained validation control. It is an alternative to [populate_by_name][pydantic.ConfigDict.populate_by_name], that enables validation by name and by alias. ///
- validate_default: bool#
Whether to validate default values during validation. Defaults to False.
- validate_return: bool#
Whether to validate the return value from call validators. Defaults to False.
- validation_error_cause: bool#
If True, Python exceptions that were part of a validation failure will be shown as an exception group as a cause. Can be useful for debugging. Defaults to False.
- Note:
Python 3.10 and older don’t support exception groups natively. <=3.10, backport must be installed: pip install exceptiongroup.
- Note:
The structure of validation errors are likely to change in future Pydantic versions. Pydantic offers no guarantees about their structure. Should be used for visual traceback debugging only.
/// version-added | v2.5 ///
- values() an object providing a view on D's values#
- class Meta[source]#
Bases:
object- database = <blissoda.import_utils.UnavailableObject object>#
- encoding = 'utf-8'#
- global_key_prefix = ''#
- index_name = ':blissoda.xrpd.models.XrpdPlotInfo:index'#
- model_key_prefix = 'blissoda.xrpd.models.XrpdPlotInfo'#
- primary_key = PrimaryKey(name='pk', field=FieldInfo(annotation=Union[str, NoneType], required=False, default=None, alias='pk', validate_default=True))#
- primary_key_creator_cls#
alias of
UlidPrimaryKey
- primary_key_pattern = '{pk}'#
- classmethod add(models, pipeline=None, pipeline_verifier=<function verify_pipeline_response>)#
- Parameters:
models (
Sequence[TypeVar(Model, bound= RedisModel)])pipeline (
Optional[Pipeline])pipeline_verifier (
Callable[...,Any])
- Return type:
Sequence[TypeVar(Model, bound= RedisModel)]
- classmethod all_pks()#
-
azim_label:
Union[str,None,ExpressionProxy] = <redis_om.model.model.ExpressionProxy object>#
- check()#
Run all validations.
-
color:
Union[str,None,ExpressionProxy] = <redis_om.model.model.ExpressionProxy object>#
- classmethod construct(_fields_set=None, **values)#
- copy(*, include=None, exclude=None, update=None, deep=False)#
Returns a copy of the model.
- !!! warning “Deprecated”
This method is now deprecated; use model_copy instead.
If you need include or exclude, use:
`python {test="skip" lint="skip"} data = self.model_dump(include=include, exclude=exclude, round_trip=True) data = {**data, **(update or {})} copied = self.model_validate(data) `- Args:
include: Optional set or mapping specifying which fields to include in the copied model. exclude: Optional set or mapping specifying which fields to exclude in the copied model. update: Optional dictionary of field-value pairs to override field values in the copied model. deep: If True, the values of fields that are Pydantic models will be deep-copied.
- Returns:
A copy of the model with included, excluded and updated fields as specified.
- Parameters:
include (AbstractSetIntStr | MappingIntStrAny | None)
exclude (AbstractSetIntStr | MappingIntStrAny | None)
update (Dict[str, Any] | None)
deep (bool)
- Return type:
Self
- classmethod db()#
- classmethod delete(pk, pipeline=None)#
Delete data at this key.
- Parameters:
pk (
Any)pipeline (
Optional[Pipeline])
- Return type:
int
- classmethod delete_many(models, pipeline=None)#
- Parameters:
models (
Sequence[RedisModel])pipeline (
Optional[Pipeline])
- Return type:
int
- dict(*, include=None, exclude=None, by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False)#
- expire(num_seconds, pipeline=None)#
- Parameters:
num_seconds (
int)pipeline (
Optional[Pipeline])
-
field_names:
Union[List[Literal['radial','azimuthal','intensity']],ExpressionProxy] = <redis_om.model.model.ExpressionProxy object>#
- classmethod find(*expressions, knn=None)#
- Parameters:
expressions (
Union[Any,Expression])knn (
Optional[KNNExpression])
- Return type:
FindQuery
- classmethod from_orm(obj)#
- Parameters:
obj (
Any)- Return type:
Self
- classmethod from_redis(res)#
- Parameters:
res (
Any)
- classmethod get(pk)[source]#
- Return type:
Type[XrpdPlotInfo]
- classmethod get_annotations()#
- get_data_array(field_name)[source]#
- Parameters:
field_name (
Literal['radial','azimuthal','intensity'])- Return type:
_Unavailable
-
hdf5_url:
Union[str,None,ExpressionProxy] = <redis_om.model.model.ExpressionProxy object>#
-
is_last_scan:
Union[bool,ExpressionProxy] = <redis_om.model.model.ExpressionProxy object>#
-
is_sum:
Union[bool,ExpressionProxy] = <redis_om.model.model.ExpressionProxy object>#
- json(*, include=None, exclude=None, by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=PydanticUndefined, models_as_dict=PydanticUndefined, **dumps_kwargs)#
- key()#
Return the Redis key for this model.
- property legend: str#
-
lima_name:
Union[str,ExpressionProxy] = <redis_om.model.model.ExpressionProxy object>#
- classmethod make_key(part)#
- Parameters:
part (
str)
- classmethod make_primary_key(pk)#
Return the Redis key for this model.
- Parameters:
pk (
Any)
- model_computed_fields = {}#
- model_config: ClassVar[ConfigDict] = {'arbitrary_types_allowed': True, 'extra': 'allow', 'from_attributes': True, 'frozen': False}#
Configuration for the model, should be a dictionary conforming to [ConfigDict][pydantic.config.ConfigDict].
- classmethod model_construct(_fields_set=None, **values)#
Creates a new instance of the Model class with validated data.
Creates a new model setting __dict__ and __pydantic_fields_set__ from trusted or pre-validated data. Default values are respected, but no other validation is performed.
- !!! note
model_construct() generally respects the model_config.extra setting on the provided model. That is, if model_config.extra == ‘allow’, then all extra passed values are added to the model instance’s __dict__ and __pydantic_extra__ fields. If model_config.extra == ‘ignore’ (the default), then all extra passed values are ignored. Because no validation is performed with a call to model_construct(), having model_config.extra == ‘forbid’ does not result in an error if extra values are passed, but they will be ignored.
- Args:
- _fields_set: A set of field names that were originally explicitly set during instantiation. If provided,
this is directly used for the [model_fields_set][pydantic.BaseModel.model_fields_set] attribute. Otherwise, the field names from the values argument will be used.
values: Trusted or pre-validated data dictionary.
- Returns:
A new instance of the Model class with validated data.
- model_copy(*, update=None, deep=False)#
- !!! abstract “Usage Documentation”
[model_copy](../concepts/models.md#model-copy)
Returns a copy of the model.
- !!! note
The underlying instance’s [__dict__][object.__dict__] attribute is copied. This might have unexpected side effects if you store anything in it, on top of the model fields (e.g. the value of [cached properties][functools.cached_property]).
- Args:
- update: Values to change/add in the new model. Note: the data is not validated
before creating the new model. You should trust this data.
deep: Set to True to make a deep copy of the model.
- Returns:
New model instance.
- model_dump(*, mode='python', include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False, polymorphic_serialization=None)#
- !!! abstract “Usage Documentation”
[model_dump](../concepts/serialization.md#python-mode)
Generate a dictionary representation of the model, optionally specifying which fields to include or exclude.
- Args:
- mode: The mode in which to_python should run.
If mode is ‘json’, the output will only contain JSON serializable types. If mode is ‘python’, the output may contain non-JSON-serializable Python objects.
include: A set of fields to include in the output. exclude: A set of fields to exclude from the output. context: Additional context to pass to the serializer. by_alias: Whether to use the field’s alias in the dictionary key if defined. exclude_unset: Whether to exclude fields that have not been explicitly set. exclude_defaults: Whether to exclude fields that are set to their default value. exclude_none: Whether to exclude fields that have a value of None. exclude_computed_fields: Whether to exclude computed fields.
While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. warnings: How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors,
“error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
- fallback: A function to call when an unknown value is encountered. If not provided,
a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A dictionary representation of the model.
- model_dump_json(*, indent=None, ensure_ascii=False, include=None, exclude=None, context=None, by_alias=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, exclude_computed_fields=False, round_trip=False, warnings=True, fallback=None, serialize_as_any=False, polymorphic_serialization=None)#
- !!! abstract “Usage Documentation”
[model_dump_json](../concepts/serialization.md#json-mode)
Generates a JSON representation of the model using Pydantic’s to_json method.
- Args:
indent: Indentation to use in the JSON output. If None is passed, the output will be compact. ensure_ascii: If True, the output is guaranteed to have all incoming non-ASCII characters escaped.
If False (the default), these characters will be output as-is.
include: Field(s) to include in the JSON output. exclude: Field(s) to exclude from the JSON output. context: Additional context to pass to the serializer. by_alias: Whether to serialize using field aliases. exclude_unset: Whether to exclude fields that have not been explicitly set. exclude_defaults: Whether to exclude fields that are set to their default value. exclude_none: Whether to exclude fields that have a value of None. exclude_computed_fields: Whether to exclude computed fields.
While this can be useful for round-tripping, it is usually recommended to use the dedicated round_trip parameter instead.
round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. warnings: How to handle serialization errors. False/”none” ignores them, True/”warn” logs errors,
“error” raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError].
- fallback: A function to call when an unknown value is encountered. If not provided,
a [PydanticSerializationError][pydantic_core.PydanticSerializationError] error is raised.
serialize_as_any: Whether to serialize fields with duck-typing serialization behavior. polymorphic_serialization: Whether to use model and dataclass polymorphic serialization for this call.
- Returns:
A JSON string representation of the model.
- property model_extra#
Get extra fields set during validation.
- Returns:
A dictionary of extra fields, or None if config.extra is not set to “allow”.
- model_fields = {'azim_label': FieldInfo(annotation=Union[str, NoneType], required=True, alias='azim_label'), 'color': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, alias='color'), 'field_names': FieldInfo(annotation=List[Literal['radial', 'azimuthal', 'intensity']], required=True, alias='field_names'), 'hdf5_url': FieldInfo(annotation=Union[str, NoneType], required=True, alias='hdf5_url'), 'is_last_scan': FieldInfo(annotation=bool, required=False, default=True, alias='is_last_scan'), 'is_sum': FieldInfo(annotation=bool, required=False, default=False, alias='is_sum'), 'lima_name': FieldInfo(annotation=str, required=True, alias='lima_name'), 'pk': FieldInfo(annotation=Union[str, NoneType], required=False, default=None, alias='pk', validate_default=True), 'radial_label': FieldInfo(annotation=str, required=True, alias='radial_label'), 'scan_name': FieldInfo(annotation=str, required=True, alias='scan_name'), 'timestamp': FieldInfo(annotation=datetime, required=True, alias='timestamp')}#
- property model_fields_set: set[str]#
Returns the set of fields that have been explicitly set on this model instance.
- Returns:
- A set of strings representing the fields that have been set,
i.e. that were not filled from defaults.
- classmethod model_json_schema(by_alias=True, ref_template='#/$defs/{model}', schema_generator=<class 'pydantic.json_schema.GenerateJsonSchema'>, mode='validation', *, union_format='any_of')#
Generates a JSON schema for a model class.
- Args:
by_alias: Whether to use attribute aliases or not. ref_template: The reference template. union_format: The format to use when combining schemas from unions together. Can be one of:
‘any_of’: Use the [anyOf](https://json-schema.org/understanding-json-schema/reference/combining#anyOf)
keyword to combine schemas (the default). - ‘primitive_type_array’: Use the [type](https://json-schema.org/understanding-json-schema/reference/type) keyword as an array of strings, containing each type of the combination. If any of the schemas is not a primitive type (string, boolean, null, integer or number) or contains constraints/metadata, falls back to any_of.
- schema_generator: To override the logic used to generate the JSON schema, as a subclass of
GenerateJsonSchema with your desired modifications
mode: The mode in which to generate the schema.
- Returns:
The JSON schema for the given model class.
- Parameters:
by_alias (
bool)ref_template (
str)schema_generator (
type[GenerateJsonSchema])mode (
Literal['validation','serialization'])union_format (
Literal['any_of','primitive_type_array'])
- Return type:
dict[str,Any]
- classmethod model_parametrized_name(params)#
Compute the class name for parametrizations of generic classes.
This method can be overridden to achieve a custom naming scheme for generic BaseModels.
- Args:
- params: Tuple of types of the class. Given a generic class
Model with 2 type variables and a concrete model Model[str, int], the value (str, int) would be passed to params.
- Returns:
String representing the new class where params are passed to cls as type variables.
- Raises:
TypeError: Raised when trying to generate concrete names for non-generic models.
- Parameters:
params (
tuple[type[Any],...])- Return type:
str
- model_post_init(context, /)#
Override this method to perform additional initialization after __init__ and model_construct. This is useful if you want to do some validation that requires the entire model to be initialized.
- Parameters:
context (
Any)- Return type:
None
- classmethod model_rebuild(*, force=False, raise_errors=True, _parent_namespace_depth=2, _types_namespace=None)#
Try to rebuild the pydantic-core schema for the model.
This may be necessary when one of the annotations is a ForwardRef which could not be resolved during the initial attempt to build the schema, and automatic rebuilding fails.
- Args:
force: Whether to force the rebuilding of the model schema, defaults to False. raise_errors: Whether to raise errors, defaults to True. _parent_namespace_depth: The depth level of the parent namespace, defaults to 2. _types_namespace: The types namespace, defaults to None.
- Returns:
Returns None if the schema is already “complete” and rebuilding was not required. If rebuilding _was_ required, returns True if rebuilding was successful, otherwise False.
- classmethod model_validate(obj, *, strict=None, extra=None, from_attributes=None, context=None, by_alias=None, by_name=None)#
Validate a pydantic model instance.
- Args:
obj: The object to validate. strict: Whether to enforce types strictly. extra: Whether to ignore, allow, or forbid extra data during model validation.
See the [extra configuration value][pydantic.ConfigDict.extra] for details.
from_attributes: Whether to extract data from object attributes. context: Additional context to pass to the validator. by_alias: Whether to use the field’s alias when validating against the provided input data. by_name: Whether to use the field’s name when validating against the provided input data.
- Raises:
ValidationError: If the object could not be validated.
- Returns:
The validated model instance.
- classmethod model_validate_json(json_data, *, strict=None, extra=None, context=None, by_alias=None, by_name=None)#
- !!! abstract “Usage Documentation”
[JSON Parsing](../concepts/json.md#json-parsing)
Validate the given JSON data against the Pydantic model.
- Args:
json_data: The JSON data to validate. strict: Whether to enforce types strictly. extra: Whether to ignore, allow, or forbid extra data during model validation.
See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context: Extra variables to pass to the validator. by_alias: Whether to use the field’s alias when validating against the provided input data. by_name: Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- Raises:
ValidationError: If json_data is not a JSON string or the object could not be validated.
- classmethod model_validate_strings(obj, *, strict=None, extra=None, context=None, by_alias=None, by_name=None)#
Validate the given object with string data against the Pydantic model.
- Args:
obj: The object containing string data to validate. strict: Whether to enforce types strictly. extra: Whether to ignore, allow, or forbid extra data during model validation.
See the [extra configuration value][pydantic.ConfigDict.extra] for details.
context: Extra variables to pass to the validator. by_alias: Whether to use the field’s alias when validating against the provided input data. by_name: Whether to use the field’s name when validating against the provided input data.
- Returns:
The validated Pydantic model.
- classmethod parse_file(path, *, content_type=None, encoding='utf8', proto=None, allow_pickle=False)#
- classmethod parse_obj(obj)#
- Parameters:
obj (
Any)- Return type:
Self
- classmethod parse_raw(b, *, content_type=None, encoding='utf8', proto=None, allow_pickle=False)#
-
pk:
Union[str,None,ExpressionProxy] = <redis_om.model.model.ExpressionProxy object>#
-
radial_label:
Union[str,ExpressionProxy] = <redis_om.model.model.ExpressionProxy object>#
- classmethod redisearch_schema()#
- save(pipeline=None)#
- Parameters:
self (
TypeVar(Model, bound= RedisModel))pipeline (
Optional[Pipeline])
- Return type:
TypeVar(Model, bound= RedisModel)
-
scan_name:
Union[str,ExpressionProxy] = <redis_om.model.model.ExpressionProxy object>#
- classmethod schema(by_alias=True, ref_template='#/$defs/{model}')#
- Parameters:
by_alias (
bool)ref_template (
str)
- Return type:
Dict[str,Any]
- classmethod schema_for_fields()#
- classmethod schema_for_type(json_path, name, name_prefix, typ, field_info, parent_type=None)#
- Parameters:
json_path (
str)name (
str)name_prefix (
str)typ (
Any)field_info (
FieldInfo)parent_type (
Optional[Any])
- Return type:
str
- classmethod schema_json(*, by_alias=True, ref_template='#/$defs/{model}', **dumps_kwargs)#
- Parameters:
by_alias (
bool)ref_template (
str)dumps_kwargs (
Any)
- Return type:
str
-
timestamp:
Union[datetime,ExpressionProxy] = <redis_om.model.model.ExpressionProxy object>#
- update(**field_values)#
Update this model instance with the specified key-value pairs.
- classmethod update_forward_refs(**localns)#
- Parameters:
localns (
Any)- Return type:
None
- classmethod validate(value)#
- Parameters:
value (
Any)- Return type:
Self
- classmethod validate_pk(v)#
- classmethod validate_primary_key()#
Check for a primary key. We need one (and only one).