{"id":16538994,"url":"https://github.com/laruss/pydantic-mongo","last_synced_at":"2025-07-12T02:36:06.952Z","repository":{"id":194115201,"uuid":"687647570","full_name":"laruss/pydantic-mongo","owner":"laruss","description":"PydanticMongo is an ODM (Object-Document Mapper) for MongoDB, built upon the foundation of Pydantic and Flask-PyMongo. This allows you to leverage Pydantic's data validation and serialization capabilities, and seamlessly integrate it with MongoDB through Flask-PyMongo.","archived":false,"fork":false,"pushed_at":"2023-11-07T14:21:31.000Z","size":55,"stargazers_count":6,"open_issues_count":0,"forks_count":1,"subscribers_count":1,"default_branch":"main","last_synced_at":"2024-10-12T18:47:25.417Z","etag":null,"topics":["flask","mongodb","orm","pydantic","pymongo","python"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":null,"status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/laruss.png","metadata":{"files":{"readme":"readme.md","changelog":null,"contributing":null,"funding":null,"license":null,"code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null}},"created_at":"2023-09-05T17:55:13.000Z","updated_at":"2024-08-01T14:24:30.000Z","dependencies_parsed_at":"2023-11-07T00:42:35.208Z","dependency_job_id":null,"html_url":"https://github.com/laruss/pydantic-mongo","commit_stats":null,"previous_names":["laruss/pydantic-mongo"],"tags_count":0,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/laruss%2Fpydantic-mongo","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/laruss%2Fpydantic-mongo/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/laruss%2Fpydantic-mongo/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/laruss%2Fpydantic-mongo/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/laruss","download_url":"https://codeload.github.com/laruss/pydantic-mongo/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":233852204,"owners_count":18740335,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["flask","mongodb","orm","pydantic","pymongo","python"],"created_at":"2024-10-11T18:47:29.583Z","updated_at":"2025-01-14T06:24:48.164Z","avatar_url":"https://github.com/laruss.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"# PydanticMongo\n\nPydanticMongo is an ODM (Object-Document Mapper) for MongoDB, built upon the foundation of Pydantic and Flask-PyMongo. This allows you to leverage Pydantic's data validation and serialization capabilities, and seamlessly integrate it with MongoDB through Flask-PyMongo.\n\n## Version\n\n0.1.4.3\n\nChanges:\n\n- updated requirements versions\n- added support for mongo indexes\n- added support for a Literal type\n- some other minor fixes\n\n## Project Structure\n```\nroot\n|-- pydantic_mongo\n|   |-- __init__.py\n|   |-- base.py\n|   |-- base_pm_model.py\n|   |-- db_ref_model.py\n|   |-- extensions.py\n|   |-- helpers.py\n|   |-- meta.py\n|   |-- mongo_model.py\n|   |-- pm_model.py\n|-- tests\n|   |-- integration\n|   |-- unit\n|-- readme.md\n|-- requirements.txt\n|-- setup.py\n```\n\n## Installation\n\nTo install `PydanticMongo`, you can clone the repository from GitHub or install it using pip:\n\n```bash\npip install git+https://github.com/laruss/pydantic-mongo\n```\n\n*Note*: Ensure you are using Python 3.10 or newer.\n\n## Usage\n\n1. Initialization:\n\n```python\nfrom pydantic_mongo import PydanticMongo\n\npm = PydanticMongo()\npm.init_app(app)\n```\n\n2. Model creation:\n\n```python\nfrom pydantic_mongo import PydanticMongoModel as PmModel\n\nclass YourModel(PmModel):\n    ...\n```\n\n2.1. Model creation with DBRefs as dicts with \"collection\", \"database\" and \"id\" keys:\n\n```python\nclass YourModel(PmModel):\n    nested_model: AnotherModel = AnotherModel()\n\ndata = {\"nested_model\": {\"collection\": \"another_models\", \"database\": \"\", \"id\": \"id\"}}\ninstance = YourModel.get_with_parse_db_refs(data)\n```\n\n2.2. Model creation with forward references:\n\n```python\nfrom __future__ import annotations\nfrom typing import ForwardRef\n\nclass YourModel(PmModel):\n    nested_model: ForwardRef(\"AnotherModel\") = AnotherModel()\n    nested_model_list: List[ForwardRef(\"AnotherModel\")] = [AnotherModel()]\n    nested_model_dict: Dict[str, ForwardRef(\"AnotherModel\")] = {\"key\": AnotherModel()}\n\nclass AnotherModel(PmModel):\n    name: str\n    \nYourModel.model_rebuild()\n\nanother_model = AnotherModel(name=\"name\").save()\ndata = {\"nested_model\": another_model, \"nested_model_list\": [another_model]}\ninstance = YourModel(**data).save()\n\n```\n\n2.3 Model creation with field indexing:\n\n```python\nfrom pydantic_mongo import PydanticMongoModel as PmModel\nfrom pymongo import IndexModel\n\nclass YourModel(PmModel):\n    name: str\n    age: int\n\n    class _MongoConfig:\n        indexes = [\n            IndexModel([(\"name\", 1)]),\n            IndexModel([(\"age\", 1)], unique=True)\n        ]\n        \nYourModel(name=\"name\", age=1).save()\nYourModel(name=\"name\", age=2).save()  # will raise PyMongoError\nYourModel(name=\"name2\", age=1).save() # will raise PyMongoError\n\n```\n\n3. Data operations:\n\n- Retrieving by ID:\n\n```python\ninstance = YourModel.get_by_id(your_id)\n```\n\n- Retrieving by filter:\n\n```python\ninstance = YourModel.get_by_filter({\"field\": \"value\"})\n```\n\n- Saving data:\n\n```python\ninstance.save()\n```\n\n- Deleting data:\n\n```python\ninstance.delete()\n```\n\n- Retrieving objects by filter:\n\n```python\nobjects = list(YourModel.objects({\"field\": \"value\"}))\n```\n\n## Key Features\n\n- `get_by_id`: Retrieve an object by its ID.\n  \n- `get_by_filter`: Retrieve an object based on a specified filter.\n\n- `save`: Save or update an object in the database.\n\n- `delete`: Delete an object from the database.\n\n- `objects`: Retrieve all objects that match a given filter.\n\n- `model_dump`: Get a dictionary representation of the model.\n\n- `model_json_schema`: Retrieve the JSON schema of the model.\n\n- `db_ref`: Get a DBRef object for the model.\n\n- `get_ref_objects`: Get the objects referenced to an object by a DBRef.\n\n## Easy Document References\n\nWith PydanticMongo, creating references to other documents is straightforward. \n\nExample:\n\n```python\nfrom pydantic_mongo import PydanticMongoModel as PmModel\n\nclass YourAwesomeChild(PmModel):\n    name: str\n\nclass YourAwesomeParent(PmModel):\n    name: str\n    children: List[YourAwesomeChild]\n\nchild = YourAwesomeChild(name=\"Victor\")\nchild.save()\n\nparent = YourAwesomeParent(name=\"Sam\", children=[child])\nparent.save()\nprint(parent)  # _id=\"id\", name=\"Sam\", children=[_id=\"id\", name=\"Victor\"]\n```\n\nIn the database, these are represented by using bson.ObjectId linking to the `your_awesome_childs` collection.\n\n`Note:` When a Document is referred as a db_ref, it won't be loaded until it is accessed. \nThis is done to avoid circular references.\n\n## Test Coverage\n\nMade with [pytest-cov](https://pypi.org/project/pytest-cov/)\n\n```bash\nName                              Stmts   Miss  Cover\n-----------------------------------------------------\npydantic_mongo/__init__.py            2      0   100%\npydantic_mongo/base.py               63      2    97%\npydantic_mongo/base_pm_model.py     145      2    99%\npydantic_mongo/db_ref_model.py       11      0   100%\npydantic_mongo/extensions.py         28      1    96%\npydantic_mongo/helpers.py            45      0   100%\npydantic_mongo/meta.py               57      3    95%\npydantic_mongo/mongo_model.py        73      1    99%\npydantic_mongo/pm_model.py           42      0   100%\n-----------------------------------------------------\nTOTAL                               466      9    98%\n```\n\n## Contributing\n\nPull requests are welcome. For major changes, please open an issue first to discuss what you would like to change.\nTo run the tests, use `pytest`:\n\n```bash\npytest ./tests/unit\npytest ./tests/integration\n```\n\n`Note:` Integration tests require a running MongoDB instance.\n\n## Conclusion\n\nPydanticMongo offers a powerful toolset for working with MongoDB in Flask applications, integrating seamlessly with Pydantic for data validation and serialization. Use it to simplify and structure your database-interaction code.\n\n## TODO\n\n- [ ] Check for all the available pydantic methods\n- [ ] Check for all the available mongo types\n- [ ] Add support of various DBRef types\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flaruss%2Fpydantic-mongo","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flaruss%2Fpydantic-mongo","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flaruss%2Fpydantic-mongo/lists"}