### Install aiomongodel Source: https://aiomongodel.readthedocs.io/en/latest/getting-started.html Install aiomongodel using pip. This command is used to add the library to your Python environment. ```bash pip install aiomongodel ``` -------------------------------- ### Update Document with $set and $inc Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Demonstrates updating a document instance in MongoDB using the `update` method. This example shows how to atomically set a field's value and increment another field's value in a single operation. ```python class User(Document): name = StrField() value = IntField(default=0) async def go(db): u = await User(name='xxx').save(db) await u.update(db, {'$set': {User.name.s: 'yyy'}, '$inc': {User.value.s: 1}}) ``` -------------------------------- ### Field Query Example Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Demonstrates how to use the `.s` property to access the MongoDB field name in queries, which can differ from the Python field name. ```python User.q(db).find({User.name.s: 'Francesco', User.is_admin.s: True}, {User.posts.s: 1, User._id.s: 0}) ``` -------------------------------- ### Async Transaction Management in Motor Source: https://aiomongodel.readthedocs.io/en/latest/getting-started.html Demonstrates how to manage asynchronous MongoDB transactions using Motor and aiomongodel. Ensure collections are created before starting a transaction. Transactions are automatically rolled back if an exception occurs within the `start_transaction` block. ```python from motor.motor_asyncio import AsyncIOMotorClient async def go(db): # create collection before using transaction await User.create_collection(db) async with await db.client.start_session() as session: try: async with s.start_transaction(): # all statements that use session inside this block # will be executed in one transaction # pass session to QuerySet await User.q(db, session=session).create(name='user') # note session param # pass session to QuerySet method await User.q(db).update_one( {User.name.s: 'user'}, {'$set': {User.is_active.s: False}}, session=session) # note session usage assert await User.q(db, session).count_documents({User.name.s: 'user'}) == 1 # session could be used in document crud methods u = await User(name='user2').save(db, session=session) await u.delete(db, session=session) raise Exception() # simulate error in transaction block except Exception: # transaction was not committed assert await User.q(db).count_documents({User.name.s: 'user'}) == 0 loop = asyncio.get_event_loop() client = AsyncIOMotorClient(io_loop=loop) db = client.aiomongodel_test loop.run_until_complete(go(db)) ``` -------------------------------- ### Document Initialization Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Initialize a Document instance with optional fields and values. The `_empty` parameter can be used to create an empty document. ```APIDOC ## Document(*, _empty=False, **kwargs) ### Parameters - **_empty** (bool) – If True return an empty document without setting any field. - **kwargs** – Fields values to set. Each key should be a field name not a mongo name of the field. ``` -------------------------------- ### with_options() Source: https://aiomongodel.readthedocs.io/en/latest/genindex.html Returns a new MotorQuerySet with specified options applied. ```APIDOC ## with_options() ### Description Returns a new MotorQuerySet with specified options applied. ### Method (Method signature for aiomongodel.queryset.MotorQuerySet) ### Parameters - **options (dict): A dictionary of options to apply to the queryset. ### Response - MotorQuerySet: A new queryset with the applied options. ``` -------------------------------- ### Document Instance Methods Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Provides instance methods for managing a specific document instance, including deletion, population, reloading, and saving. ```APIDOC ## Instance Methods ### `delete(_db, _session=None)` Delete current object from db. ### `populate_with_data(_data)` Populate document object with data. **Parameters**: - **data** (dict) – Document data in form {field_name => value}. **Returns**: Self instance. **Raises**: `AttributeError` – On wrong field name. ### `query_id` ### `reload(_db, _session=None)` Reload current object from mongodb. ### `save(_db, do_insert=False, _session=None)` Save document in mongodb. **Parameters**: - **db** – Database instance. - **do_insert** (bool) – If `True` always perform `insert_one`, else perform `replace_one` with `upsert=True`. - **session** – Motor session object. ### `to_data()` Return internal data of the document. **Returns**: Data of the document. **Return type**: OrderedDict ### `to_mongo()` Convert document to mongo format. ### `update(_db, _update_document_, _session=None)` Update current object using query. **Usage**: ```python class User(Document): name = StrField() value = IntField(default=0) async def go(db): u = await User(name='xxx').save(db) await u.update(db, {'$set': {User.name.s: 'yyy'}, '$inc': {User.value.s: 1}}) ``` ``` -------------------------------- ### Perform CRUD Operations with aiomongodel Source: https://aiomongodel.readthedocs.io/en/latest/getting-started.html Demonstrates Create, Read, Update, and Delete operations using aiomongodel's query interface. Includes creating indexes, saving documents, retrieving by ID, finding documents with filters, updating, and deleting. ```python from motor.motor_asyncio import AsyncIOMotorClient import asyncio from bson.objectid import ObjectId async def go(db): # create model's indexes await User.q(db).create_indexes() # CREATE # create using save # Note: if do_insert=False (default) save performs a replace # with upsert=True, so it does not raise if _id already exists # in db but replace document with that _id. u = await User(name='Alexandro').save(db, do_insert=True) assert u.name == 'Alexandro' assert u._id == 'Alexandro' assert u.is_active is True assert u.posts == [] assert u.quote is None # using query u = await User.q(db).create(name='Ihor', is_active=False) # READ # get by id u = await User.q(db).get('Alexandro') assert u.name == 'Alexandro' # find users = await User.q(db).find({User.is_active.s: True}).to_list(10) assert len(users) == 2 # using for loop users = [] async for user in User.q(db).find({User.is_active.s: False}): users.append(user) assert len(users) == 1 # in Python 3.6 an up use async comprehensions users = [user async for user in User.q(db).find({})] assert len(users) == 3 # UPDATE u = await User.q(db).get('Ihor') u.is_active = True await u.save(db) assert (await User.q(db).get('Ihor')).is_active is True # using update (without data validation) # object is reloaded from db after update. await u.update(db, {'$push': {User.posts.s: ObjectId()}}) # DELETE u = await User.q(db).get('Ihor') await u.delete(db) loop = asyncio.get_event_loop() client = AsyncIOMotorClient(io_loop=loop) db = client.aiomongodel_test loop.run_until_complete(go(db)) ``` -------------------------------- ### Aiomongodel Utils Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html This section covers utility functions that assist with common tasks within Aiomongodel, such as string manipulation and class importing. ```APIDOC ## Utils ### `aiomongodel.utils.snake_case` Converts a CamelCase string to snake_case. **Parameters:** - `camel_case` (str): The CamelCase string to convert. ### `aiomongodel.utils.import_class` Imports a class by its absolute import path. The class is cached after importing. **Parameters:** - `absolute_import_path` (str): The absolute path of the class to import. **Returns:** - type: The imported class object. **Raises:** - `ImportError`: If the class cannot be imported by the given path. **Example:** ```python Document = import_class('aiomongodel.document.Document') ``` ``` -------------------------------- ### Define User and ActiveUser Models Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Define a base User model with fields like name, is_active, and created, including unique and sorted indexes. Then, define an ActiveUser model inheriting from User, specifying the same collection but with a default query to filter for active users. ```python from pymongo import IndexModel, ASCENDING, DESCENDING class User(Document): name = StrField(regex=r'^[a-zA-Z]{6,20}$') is_active = BoolField(default=True) created = DateTimeField(default=lambda: datetime.utcnow()) class Meta: # define a collection name collection = 'users' # define collection indexes. Use # await User.q(db).create_indexes() # to create them on application startup. indexes = [ IndexModel([('name', ASCENDING)], unique=True), IndexModel([('created', DESCENDING)])] # order by `created` field by default default_sort = [('created', DESCENDING)] class ActiveUser(User): is_active = BoolField(default=True, choices=[True]) class Meta: collection = 'users' # specify a default query to work ONLY with # active users. So for example # await ActiveUser.q(db).count({}) # will count ONLY active users. default_query = {'is_active': True} ``` -------------------------------- ### Perform Database Operations with Aiomongodel Source: https://aiomongodel.readthedocs.io/en/latest/getting-started.html Execute database queries including finding documents with cursors, finding a single document, updating, and deleting documents. Use `User.q(db)` to initiate query operations. ```python async def go(db): # find returns a cursor cursor = User.q(db).find({}, {'_id': 1}).skip(1).limit(2) async for user in cursor: print(user.name) assert user.is_active is None # we used projection # find one user = await User.q(db).find_one({User.name.s: 'Alexandro'}) assert user.name == 'Alexandro' # update await User.q(db).update_many( {User.is_active.s: True}, {'$set': {User.is_active.s: False}}) # delete await User.q(db).delete_many({}) ``` -------------------------------- ### from_data(data) Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Class method to create a document instance from a user-provided dictionary. ```APIDOC ## from_data(data) ### Description Class method to create a document instance from a user-provided dictionary. ### Parameters - **data** (dict) – Data dict in form {field_name => value}. ### Returns - Document instance. ``` -------------------------------- ### from_mongo(data) Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Class method to create a document instance from data loaded from MongoDB. ```APIDOC ## from_mongo(data) ### Description Class method to create a document instance from data loaded from MongoDB. ### Parameters - **data** (dict) – SON data loaded from mongodb. ### Returns - Document instance. ``` -------------------------------- ### Import Class Utility Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Imports a class dynamically using its absolute import path. The imported class is cached for subsequent calls. ```python Document = import_class('aiomongodel.document.Document') ``` -------------------------------- ### to_list() Source: https://aiomongodel.readthedocs.io/en/latest/genindex.html Converts a MotorQuerySetCursor to a list of documents. ```APIDOC ## to_list() ### Description Converts the MotorQuerySetCursor to a list of documents. ### Method (Method signature for aiomongodel.queryset.MotorQuerySetCursor) ### Parameters None ### Response - list: A list of documents. ``` -------------------------------- ### populate_with_data(data) Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Populates an existing document object with data from a dictionary. Raises AttributeError on wrong field name. ```APIDOC ## populate_with_data(data) ### Description Populates an existing document object with data from a dictionary. ### Parameters - **data** (dict) – Document data in form {field_name => value}. ### Returns - Self instance. ### Raises - `AttributeError` – On wrong field name. ``` -------------------------------- ### Define MongoDB Models with aiomongodel Source: https://aiomongodel.readthedocs.io/en/latest/getting-started.html Define asynchronous MongoDB models by inheriting from `aiomongodel.Document` or `aiomongodel.EmbeddedDocument`. Includes field definitions, meta options for collection and indexes, and synonym fields. ```python # models.py from datetime import datetime from pymongo import IndexModel, DESCENDING from aiomongodel import Document, EmbeddedDocument from aiomongodel.fields import ( StrField, BoolField, ListField, EmbDocField, RefField, SynonymField, IntField, FloatField, DateTimeField, ObjectIdField) class User(Document): _id = StrField(regex=r'[a-zA-Z0-9_]{3, 20}') is_active = BoolField(default=True) posts = ListField(RefField('models.Post'), default=lambda: list()) quote = StrField(required=False) # create a synonym field name = SynonymField(_id) class Meta: collection = 'users' class Post(Document): # _id field will be added automatically as # _id = ObjectIdField(defalut=lambda: ObjectId()) title = StrField(allow_blank=False, max_length=50) body = StrField() created = DateTimeField(default=lambda: datetime.utcnow()) views = IntField(default=0) rate = FloatField(default=0.0) author = RefField(User, mongo_name='user') comments = ListField(EmbDocField('models.Comment'), default=lambda: list()) class Meta: collection = 'posts' indexes = [IndexModel([('created', DESCENDING)])] default_sort = [('created', DESCENDING)] class Comment(EmbeddedDocument): _id = ObjectIdField(default=lambda: ObjectId()) author = RefField(User) body = StrField() # `s` property of the fields can be used to get a mongodb string name # to use in queries assert User._id.s == '_id' assert User.name.s == '_id' # name is synonym assert Post.title.s == 'title' assert Post.author.s == 'user' # field has mongo_name assert Post.comments.body.s == 'comments.body' # compound name ``` -------------------------------- ### IntField Class Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Represents an integer field. ```APIDOC ## Class: IntField ### Description Integer field. ### Parameters - **kwargs** - Other arguments from `Field`. ``` -------------------------------- ### Inherit Models with Same Collection in Aiomongodel Source: https://aiomongodel.readthedocs.io/en/latest/getting-started.html Define multiple models that share the same database collection by specifying the `collection` in their `Meta` class. Use `from_mongo` to instantiate the correct model based on data. ```python class Mixin: is_active = BoolField(default=True) class User(Mixin, Document): _id = StrField() role = StrField() name = SynonymField(_id) class Meta: collection = 'users' @classmethod def from_mongo(cls, data): # create appropriate model when loading from db if data['role'] == 'customer': return super(User, Customer).from_mongo(data) if data['role'] == 'admin': return super(User, Admin).from_mongo(data) class Customer(User): role = StrField(default='customer', choices=['customer']) # overwrite role field address = StrField() class Meta: collection = 'users' default_query = {User.role.s: 'customer'} class Admin(User): role = StrField(default='admin', choices=['admin']) # overwrite role field rights = ListField(StrField(), default=lambda: list()) class Meta: collection = 'users' default_query = {User.role.s: 'admin'} ``` -------------------------------- ### update() Source: https://aiomongodel.readthedocs.io/en/latest/genindex.html Updates a Document instance with new data. ```APIDOC ## update() ### Description Updates the Document instance with new data. ### Method (Method signature for aiomongodel.Document) ### Parameters - data (dict): A dictionary containing the fields to update. ### Response None ``` -------------------------------- ### Meta Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html A class used for storing metadata about a Document, such as collection name, indexes, and query settings. ```APIDOC ## Meta(**kwargs) ### Description Storage for Document meta info. ### Attributes - **collection_name**: Name of the document’s db collection (note that it should be specified as `collection` Meta class attribute). - **indexes**: List of `pymongo.IndexModel` for collection. - **queryset**: Query set class to query documents. - **default_query**: Each query in query set will be extended using this query through `$and` operator. - **default_sort**: Default sort expression to order documents in `find`. - **fields**: OrderedDict of document fields as `{field_name => field}`. - **fields_synonyms**: Dict of synonyms for field as `{field_name => synonym_name}`. - **codec_options**: Collection’s codec options. - **read_preference**: Collection’s read preference. - **write_concern**: Collection’s write concern. - **read_concern**: Collection’s read concern. - **OPTIONS**: Set of available options: {'fields', 'fields_synonyms', 'default_sort', 'indexes', 'read_concern', 'collection', 'read_preference', 'write_concern', 'codec_options', 'queryset', 'default_query'} ``` -------------------------------- ### Define Model Inheritance in Aiomongodel Source: https://aiomongodel.readthedocs.io/en/latest/getting-started.html Create a hierarchy of models by inheriting from `aiomongodel.Document` or `aiomongodel.EmbeddedDocument`. Fields are inherited, but meta options are not. Fields can be overwritten in child classes. ```python class Mixin: value = IntField() class Parent(Document): name = StrField() class Child(Mixin, Parent): # also has value and name fields rate = FloatField() class OtherChild(Child): # also has rate and name fields value = FloatField() # overwrite value field from Mixin class SubDoc(Mixin, EmbeddedDocument): # has value field pass ``` -------------------------------- ### DateTimeField Class Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Represents a date and time field, based on `datetime.datetime`. ```APIDOC ## Class: DateTimeField ### Description Date and time field based on datetime.datetime. ### Parameters - **kwargs** - Other arguments from `Field`. ### Methods - **from_data(value)**: Converts value from user provided data to field type. ``` -------------------------------- ### SynonymField Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Creates a synonym name for a real document field, allowing an alternative name for an existing field. ```APIDOC ## Class: aiomongodel.fields.SynonymField ### Description Create synonym name for real field. Create synonym for real document’s field. ### Parameters * **original_field** (Field instance or string) - Field instance or string name of field. ### Example ```python class Doc(Document): _id = StrField() name = SynonymField(_id) class OtherDoc(Document): # _id field will be added automaticly. obj_id = SynonymField('_id') ``` ``` -------------------------------- ### Document Class Methods Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Provides class methods for interacting with the MongoDB collection associated with the Document. ```APIDOC ## Class Methods ### `coll(_db)` Return raw collection object. **Parameters**: - **db** – Motor database object. **Returns**: Raw Motor collection object. **Return type**: MotorCollection ### `create(_db, _session=None, **_kwargs)` Create document in mongodb. **Parameters**: - **db** – Database instance. - **session** – Motor session object. - **kwargs** – Document’s fields values. **Returns**: Created document instance. **Raises**: `ValidationError` – If some fields are not valid. ### `create_collection(_db, _session=None)` Create collection for documents. **Parameters**: - **db** – Database object. **Returns**: Collection object. ### `from_data(_data)` Create document from user provided data. **Parameters**: - **data** (dict) – Data dict in form {field_name => value}. **Returns**: Document isinstance. ### `from_mongo(_data)` Create document from mongo data. **Parameters**: - **data** (dict) – SON data loaded from mongodb. **Returns**: Document instance. ### `q(_db, _session=None)` Return queryset object. **Parameters**: - **db** – Motor database object. - **session** – Motor client session object. **Returns**: Queryset object. **Return type**: MotorQuerySet ``` -------------------------------- ### to_mongo() Source: https://aiomongodel.readthedocs.io/en/latest/genindex.html Converts a Document or EmbeddedDocument instance to a MongoDB-compatible dictionary. ```APIDOC ## to_mongo() ### Description Converts the Document, EmbeddedDocument, or field instance to a MongoDB-compatible dictionary. ### Method (Method signature for aiomongodel.Document, aiomongodel.EmbeddedDocument, and various aiomongodel.fields) ### Parameters None ### Response - dict: A dictionary suitable for MongoDB insertion or update. ``` -------------------------------- ### FloatField Class Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Represents a floating-point number field. ```APIDOC ## Class: FloatField ### Description Float field. ### Parameters - **kwargs** - Other arguments from `Field`. ``` -------------------------------- ### RefField Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Represents a reference field, allowing references to other documents. ```APIDOC ## Class: aiomongodel.fields.RefField ### Description Reference field. Create Reference field. ### Parameters * **document_class** (Document subclass or string path) - A subclass of the `aiomongodel.Document` class or string with absolute path to such class. * **kwargs** - Other arguments from `Field`. ### Methods #### `from_data(value)` Convert value from user provided data to field type. Parameters: * **value** (any) - Value provided by user. Returns: Converted value or value as is if error occured. If value is `None` return `None`. #### `from_mongo(value)` Convert value from mongo format to python field format. #### `to_mongo(value)` Convert value to mongo format. ``` -------------------------------- ### AnyField Class Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html A field that can store any type of value. It stores the value as is. ```APIDOC ## Class: AnyField ### Description Any type field. Can store any type of value. Store a value as is. ### Methods - **from_data(value)**: Converts value from user provided data to field type. ``` -------------------------------- ### to_data() Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Returns the internal data of the document, which may include embedded documents or lists. ```APIDOC ## to_data() ### Description Returns the internal data of the document. Internal data can contain embedded document objects, lists etc. ### Returns - Data of the document. ### Return type - OrderedDict ``` -------------------------------- ### EmbeddedDocument Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Base class for embedded documents. Allows initialization with optional empty state or field values. ```APIDOC ## EmbeddedDocument(**kwargs, empty=False) ### Description Base class for embedded documents. Allows initialization with optional empty state or field values. ### Parameters - **empty** (bool) – If True return an empty document without setting any field. - **kwargs** – Fields values to set. Each key should be a field name not a mongo name of the field. ``` -------------------------------- ### Field Class Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html The base class for all fields in aiomongodel. It handles core field properties like name, required status, default values, and MongoDB naming. ```APIDOC ## Class: Field ### Description Base class for all fields. ### Parameters - **required** (bool) - Is field required. Defaults to `True`. - **default** - Default value for a field. Defaults to `_Empty`. - **mongo_name** (str) - Name of the field in MongoDB. Defaults to `None`. - **name** (str) - Name of the field. Defaults to `None`. - **allow_none** (bool) - Can field be assigned with `None`. Defaults to `False`. - **choices** (dict, set) - Possible values for field. Defaults to `None`. ### Methods - **name**: str - Name of the field. - **mongo_name**: str - Name of the field in mongodb. - **required**: bool - Is field required. - **allow_none**: bool - Can field be assigned with `None`. - **default**: Any - Default value for field. - **choices**: dict, set - Dict or set of choices for a field. - **from_data(value)**: Converts value from user provided data to field type. - **from_mongo(value)**: Converts value from mongo format to python field format. - **s**: str - Return mongodb name of the field. ``` -------------------------------- ### validate() Source: https://aiomongodel.readthedocs.io/en/latest/genindex.html Validates the Document or EmbeddedDocument instance. ```APIDOC ## validate() ### Description Validates the Document or EmbeddedDocument instance. ### Method (Method signature for aiomongodel.Document and aiomongodel.EmbeddedDocument) ### Parameters None ### Response None ### Raises - ValidationError: If the document is invalid. ``` -------------------------------- ### collection(db) Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Retrieves the collection object for the documents, given a database object. ```APIDOC ## collection(db) ### Description Retrieves the collection object for the documents, given a database object. ### Parameters - **db** (Database object) – Database object. ### Returns - Collection object. ``` -------------------------------- ### Aiomongodel Exceptions Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html This section describes the custom exceptions provided by the Aiomongodel library, which are used to handle various error conditions during database operations and data validation. ```APIDOC ## Exceptions ### `aiomongodel.errors.AioMongodelException` Base class for all Aiomongodel exceptions. ### `aiomongodel.errors.DocumentNotFoundError` Raised when a document is not found in the database. ### `aiomongodel.errors.DuplicateKeyError` Raised when a unique key constraint error occurs. **Parameters:** - `message` (str): String representation of the `pymongo.errors.DuplicateKeyError`. **Attributes:** - `index_name` (str): The name of the unique index that caused the error. ### `aiomongodel.errors.Error` Base class for Aiomongodel errors. ### `aiomongodel.errors.StopValidation` Raised to stop the validation process for a field. ### `aiomongodel.errors.ValidationError` Raised on model validation errors. **Parameters:** - `error` (str or dict): Can contain a simple error string or a dictionary of nested validation errors. - `constraint` (any): A constraint value for the validation error, used in error message formatting. **Methods:** - `as_dict(translation=None)`: Extracts all errors from the `self.error` attribute. Returns a string if `self.error` is a string, otherwise returns a dictionary of errors. ``` -------------------------------- ### to_data() Source: https://aiomongodel.readthedocs.io/en/latest/genindex.html Converts a Document or EmbeddedDocument instance to a Python dictionary. ```APIDOC ## to_data() ### Description Converts the Document or EmbeddedDocument instance to a Python dictionary. ### Method (Method signature for aiomongodel.Document and aiomongodel.EmbeddedDocument) ### Parameters None ### Response - dict: A dictionary representation of the document. ``` -------------------------------- ### MotorQuerySetCursor Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Represents a cursor for iterating over query results, based on Motor's cursor. ```APIDOC ## MotorQuerySetCursor Cursor based on motor cursor. ### Methods - **clone()**: Get copy of this cursor. - **to_list(length)**: Return list of documents. - Parameters: **length** – Number of items to return. - Returns: List of document model instances. - Return type: list ``` -------------------------------- ### validate() Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Validates the data within a document instance. Raises ValidationError if the data is invalid. ```APIDOC ## validate() ### Description Validates the data within a document instance. ### Returns - Self instance. ### Raises - `ValidationError` – If document’s data is not valid. ``` -------------------------------- ### validate_document() Source: https://aiomongodel.readthedocs.io/en/latest/genindex.html Validates a document instance as a class method. ```APIDOC ## validate_document() ### Description Validates a document instance as a class method. ### Method (Class method signature for aiomongodel.Document and aiomongodel.EmbeddedDocument) ### Parameters - data (dict): The document data to validate. ### Response None ### Raises - ValidationError: If the document data is invalid. ``` -------------------------------- ### ListField Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Represents a list field, enforcing type constraints on its items and optionally setting minimum and maximum lengths. ```APIDOC ## Class: aiomongodel.fields.ListField ### Description List field. Create List field. ### Parameters * **item_field** (Field) - Instance of the field to reflect list items’ type. * **min_length** (int) - Minimum length of the list. Defaults to `None`. * **max_length** (int) - Maximum length of the list. Defaults to `None`. * **kwargs** - Other arguments from `Field`. ### Raises * `TypeError` - If item_field is not instance of the `Field` subclass. ### Methods #### `from_data(value)` Convert value from user provided data to field type. Parameters: * **value** (any) - Value provided by user. Returns: Converted value or value as is if error occured. If value is `None` return `None`. #### `from_mongo(value)` Convert value from mongo format to python field format. #### `to_mongo(value)` Convert value to mongo format. ``` -------------------------------- ### EmailField Class Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html A specialized string field for email addresses, with a default regex pattern for validation. ```APIDOC ## Class: EmailField ### Description Email field. ### Parameters - **regex** (str, re.regex) - Pattern for email address. Defaults to `re.compile('^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+$')`. - **kwargs** - Other arguments from `Field` and `StrField`. ``` -------------------------------- ### Validate Model Data with Aiomongodel Source: https://aiomongodel.readthedocs.io/en/latest/getting-started.html Use the `validate` method to check model data for validity. An `aiomongodel.errors.ValidationError` is raised for invalid data. Note that model creation or assignment with invalid data does not raise errors, so explicit validation before saving is crucial. ```python class Model(Document): name = StrField(max_length=7) value = IntField(gt=5, lte=13) data = FloatField() def go(): m = Model(name='xxx', value=10, data=1.6) # validate data # should not raise any error m.validate() # invalid data # note that there are no errors while creating # model with invalid data invalid = Model(name='too long string', value=0) try: invalid.validate() except aiomongodel.errors.ValidationError as e: assert e.as_dict() == { 'name': 'length is greater than 7', 'value': 'value should be greater than 5', 'data': 'field is required' } # using translation - you can translate messages # to your language or modify them translation = { "field is required": "This field is required", "length is greater than {constraint}": ("Length of the field " "is greater than " "{constraint} characters"), # see all error messages in ValidationError docs # for missed messages default messages will be used } assert e.as_dict(translation=translation) == { 'name': 'Length of the field is greater than 7 characters', 'value': 'value should be greater than 5', 'data': 'This field is required' } ``` -------------------------------- ### Aiomongodel Validation Error Translations Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Provides a template for translating default validation error messages. Use this to customize error feedback for different locales. ```python translation = { "field is required": "", "none value is not allowed": "", "blank value is not allowed": "", "invalid value type": "", "value does not match any variant": "", "value does not match pattern {constraint}": "", "length is less than {constraint}": "", "length is greater than {constraint}": "", "value is less than {constraint}": "", "value is greater than {constraint}": "", "list length is less than {constraint}": "", "list length is greater than {constraint}": "", "value is not a valid email address": "", } ``` -------------------------------- ### write_concern Source: https://aiomongodel.readthedocs.io/en/latest/genindex.html Meta attribute for specifying write concern. ```APIDOC ## write_concern ### Description Meta attribute for specifying the write concern for database operations. ### Attribute (Attribute definition for aiomongodel.document.Meta) ### Type - str or int: The write concern level. ``` -------------------------------- ### update_many() Source: https://aiomongodel.readthedocs.io/en/latest/genindex.html Updates multiple documents in the collection that match the query. ```APIDOC ## update_many() ### Description Updates multiple documents in the collection that match the query. ### Method (Method signature for aiomongodel.queryset.MotorQuerySet) ### Parameters - filter (dict): The query filter to select documents. - update (dict): The update operations to apply. ### Response - UpdateResult: An object containing information about the update operation. ``` -------------------------------- ### MotorQuerySet Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Provides methods for querying and manipulating documents in a MongoDB collection using Motor. ```APIDOC ## MotorQuerySet QuerySet based on Motor query syntax. ### Methods - **aggregate(pipeline, **kwargs)**: Return Aggregation cursor. - **clone()**: Return a copy of queryset. - **count(query={}, **kwargs)**: Count documents in collection. - **count_documents(query={}, **kwargs)**: Count documents in collection. - **create(**kwargs)**: Create document. - Parameters: **kwargs** – fields of the document. - Returns: Document instance. - **create_indexes()**: Create document’s indexes defined in Meta class. - **delete_many(query, **kwargs)**: Delete many documents. - **delete_one(query, **kwargs)**: Delete one document. - **find(query={}, *args, sort=None, **kwargs)**: Find documents by query. - Returns: Cursor to get actual data. - Return type: MotorQuerySetCursor - **find_one(query={}, *args, **kwargs)**: Find one document. - Arguments are the same as for `motor.Collection.find_one`. - This method does not returns `None` if there is no documents for given query but raises `aiomongodel.errors.DocumentNotFoundError`. - Returns: Document model instance. - Raises: `aiomongodel.errors.DocumentNotFoundError` – If there is no documents for given query. - **get(__id, *args, **kwargs)**: Get document by its _id. - **insert_many(*args, **kwargs)**: Insert many documents. - Returns: List of inserted `_id` values. - Return type: list - **insert_one(*args, **kwargs)**: Insert one document. - Returns: Inserted `_id` value. - Raises: `aiomongodel.errors.DuplicateKeyError` – On duplicate key error. - **replace_one(query, *args, **kwargs)**: Replace one document. - Returns: Number of modified documents. - Return type: int - Raises: `aiomongodel.errors.DuplicateKeyError` – On duplicate key error. - **update_many(query, *args, **kwargs)**: Update many documents. - Returns: Number of modified documents. - Return type: int - Raises: `aiomongodel.errors.DuplicateKeyError` – On duplicate key error. - **update_one(query, *args, **kwargs)**: Update one document. - Returns: Number of modified documents. - Return type: int - Raises: `aiomongodel.errors.DuplicateKeyError` – On duplicate key error. - **with_options(**kwargs)**: Change collection options. ``` -------------------------------- ### StrField Class Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Represents a string field with options for regular expression validation, allowing blank strings, and setting minimum/maximum lengths. ```APIDOC ## Class: StrField ### Description String field. ### Parameters - **regex** (str) - Regular expression for field’s values. Defaults to `None`. - **allow_blank** (bool) - Can field be assigned with blank string. Defaults to `False`. - **min_length** (int) - Minimum length of field’s values. Defaults to `None`. - **max_length** (int) - Maximum length of field’s values. Defaults to `None`. - **kwargs** - Other arguments from `Field`. ``` -------------------------------- ### update_one() Source: https://aiomongodel.readthedocs.io/en/latest/genindex.html Updates a single document in the collection that matches the query. ```APIDOC ## update_one() ### Description Updates a single document in the collection that matches the query. ### Method (Method signature for aiomongodel.queryset.MotorQuerySet) ### Parameters - filter (dict): The query filter to select the document. - update (dict): The update operations to apply. ### Response - UpdateResult: An object containing information about the update operation. ``` -------------------------------- ### validate_document(document) Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Class method to validate a given document instance. Raises ValidationError if the document's data is invalid. ```APIDOC ## validate_document(document) ### Description Class method to validate a given document instance. ### Parameters - **document** (Document instance) – Document instance to validate. ### Raises - `ValidationError` – If document’s data is not valid. ``` -------------------------------- ### EmbDocField Class Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Represents an embedded document field, which can be a subclass of `aiomongodel.EmbeddedDocument` or a string path to such a class. ```APIDOC ## Class: EmbDocField ### Description Embedded Document Field. ### Parameters - **document_class** - A subclass of the `aiomongodel.EmbeddedDocument` class or string with absolute path to such class. - **kwargs** - Other arguments from `Field`. ### Methods - **from_data(value)**: Converts value from user provided data to field type. ``` -------------------------------- ### DecimalField Class Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Represents a decimal number field, compatible with MongoDB 3.4+. ```APIDOC ## Class: DecimalField ### Description Decimal number field. This field can be used only with MongoDB 3.4+. ### Parameters - **kwargs** - Other arguments from `Field`. ### Methods - **from_mongo(value)**: Converts value from mongo format to python field format. - **to_mongo(value)**: Converts value to mongo format. ``` -------------------------------- ### ObjectIdField Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Represents an ObjectId field, handling conversion to and from MongoDB ObjectId format. ```APIDOC ## Class: aiomongodel.fields.ObjectIdField ### Description ObjectId field. ### Methods #### `from_data(value)` Convert value to ObjectId. Parameters: * **value** (ObjectId, str) - ObjectId value or 24-character hex string. Returns: None or ObjectId value. If value is not ObjectId and can’t be converted return as is. ``` -------------------------------- ### Define SynonymField in aiomongodel Source: https://aiomongodel.readthedocs.io/en/latest/api/index.html Use SynonymField to create an alias for an existing field within a document. This is useful for providing alternative names or simplifying access to fields. ```python class Doc(Document): _id = StrField() name = SynonymField(_id) class OtherDoc(Document): # _id field will be added automaticly. obj_id = SynonymField('_id') ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.