{"id":24559236,"url":"https://github.com/parcellab/django-mongo-backend","last_synced_at":"2026-05-18T18:38:59.608Z","repository":{"id":218042097,"uuid":"745441454","full_name":"parcelLab/django-mongo-backend","owner":"parcelLab","description":"MongoDB database adapter \u0026 compiler for Django","archived":false,"fork":false,"pushed_at":"2025-02-12T07:59:10.000Z","size":98,"stargazers_count":0,"open_issues_count":2,"forks_count":0,"subscribers_count":10,"default_branch":"main","last_synced_at":"2025-02-12T08:51:39.553Z","etag":null,"topics":["django","open-source","team-backend"],"latest_commit_sha":null,"homepage":null,"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/parcelLab.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,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null}},"created_at":"2024-01-19T10:43:52.000Z","updated_at":"2025-02-12T07:58:12.000Z","dependencies_parsed_at":"2024-01-19T12:08:56.521Z","dependency_job_id":"11583bdc-bd3d-48cc-8312-a106d7c1d604","html_url":"https://github.com/parcelLab/django-mongo-backend","commit_stats":null,"previous_names":["parcellab/django-mongo-backend"],"tags_count":2,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parcelLab%2Fdjango-mongo-backend","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parcelLab%2Fdjango-mongo-backend/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parcelLab%2Fdjango-mongo-backend/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/parcelLab%2Fdjango-mongo-backend/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/parcelLab","download_url":"https://codeload.github.com/parcelLab/django-mongo-backend/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":243922336,"owners_count":20369382,"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":["django","open-source","team-backend"],"created_at":"2025-01-23T06:16:00.092Z","updated_at":"2026-05-18T18:38:59.597Z","avatar_url":"https://github.com/parcelLab.png","language":"Python","funding_links":[],"categories":[],"sub_categories":[],"readme":"## Django backend for MongoDB\n\nDjango backend for MongoDB.\n\nSupports:\n- Column mappings to MongoDB documents\n- Single table (collection) inheritance and single table OneToOne relationships\n- Filters (filter/exclude)\n\n## Setup / Configuration\n\nNot supported as primary database, as Django contrib apps rely on Integer primary keys in built in migrations (and\nbecause it is a use case that is not a priority at the moment).\n\n```python\n# settings.py\nDATABASES = {\n    # or any other primary databse\n    \"default\": {\n        \"ENGINE\": \"django.db.backends.sqlite3\",\n        \"NAME\": BASE_DIR / \"db.sqlite3\",\n    },\n    # mongodb database, Client constructor options are passe in 'CLIENT', the database name in 'NAME'\n    \"mongodb\": {\n        \"ENGINE\": \"django_mongodb\",\n        \"NAME\": \"django_mongodb\",\n        \"CONN_MAX_AGE\": 120,\n        \"CLIENT\": {\n            \"host\": os.environ.get(\"MONGODB_URL\"),\n        },\n    },\n}\n# A database is required\nDATABASE_ROUTERS = [\"testproject.router.DatabaseRouter\"]\n```\n\nUsing the database in models requires a DatabaseRouter, which could look like this\n```python\nclass DatabaseRouter:\n    def db_for_read(self, model, **hints):\n        if model._meta.app_label == \"mymongoapp\":\n            return \"default\"\n        return \"default\"\n\n    def db_for_write(self, model, **hints):\n        if model._meta.app_label == \"mymongoapp\":\n            return \"default\"\n        return \"default\"\n\n    def allow_relation(self, obj1, obj2, **hints):\n        if obj1._meta.app_label == obj2._meta.app_label:\n            return True\n        return None\n\n    def allow_migrate(self, db, app_label, model_name=None, **hints):\n        if app_label == \"mymongoapp\":\n            # we are disabling migrations, as MongoDB is schema-less. Alerts, such as renaming fields, etc. are not supported\n            return False\n        return None\n```\n\nFinally we are going to change the default primary key of the app using MongoDB (if that is the case, otherwise add\nObjectIdAutoField to the models, where you need it).\n\n```python\n# apps.py\nclass TestappConfig(AppConfig):\n    default_auto_field = \"django_mongodb.models.ObjectIdAutoField\"\n    name = \"mymongoapp\"\n```\n\n### Defining Models\nA simple model, in an app, which has `ObjectIdAutoField` as `default_auto_field`\n\n```python\nclass MyModel(models.Model):\n    json_field = JSONField()\n    name = models.CharField(max_length=100)\n    datetime_field = models.DateTimeField(auto_now_add=True)\n    time_field = models.TimeField(auto_now_add=True)\n    date_field = models.DateField(auto_now_add=True)\n```\n\n#### DecimalField Support\n\nDjango-mongo-backend supports `DecimalField` for storing decimal values as BSON Decimal128:\n\n- **Django 5.2+**: Use the built-in `django.db.models.DecimalField` directly\n- **Django \u003c 5.2**: Use `django_mongodb.models.DecimalField` for proper MongoDB compatibility\n\n```python\n# For Django 5.2+\nfrom django.db import models\n\nclass Product(models.Model):\n    price = models.DecimalField(max_digits=10, decimal_places=2)\n\n# For Django \u003c 5.2\nfrom django_mongodb.models import DecimalField\n\nclass Product(models.Model):\n    price = DecimalField(max_digits=10, decimal_places=2)\n```\n\nSingle table inheritance\n\n```python\nclass SameTableChild(MyModel):\n    my_model_ptr = models.OneToOneField(\n        MyModel,\n        on_delete=models.CASCADE,\n        parent_link=True,\n        related_name=\"same_table_child\",\n        # pointer to the primary key of the parent model\n        db_column=\"_id\",\n    )\n    extended = models.CharField(max_length=100)\n\n    class Meta:\n        # We are using the parent collection as db_table\n        db_table = \"mymongoapp_mymodel\"\n```\n\nSingle table `OneToOne` relationships\n\n```python\nclass SameTableOneToOne(models.Model):\n    dummy_model = models.OneToOneField(\n        MyModel,\n        primary_key=True,\n        on_delete=models.CASCADE,\n        related_name=\"extends\",\n        db_column=\"_id\",\n    )\n    extra = models.CharField(max_length=100)\n\n    class Meta:\n        # we are using the same collection to persist one-to-one relationships\n        db_table = \"mymongoapp_mymodel\"\n```\n\n### Querying\n\n```python\n# get all objects\nMyModel.objects.all()\n\n# get all objects, which have a name in list [\"foo\", \"bar\"]\nMyModel.objects.filter(name_in=[\"foo\", \"bar\"])\n\n# select related with single table inheritance and one to one relationships\nMyModel.objects.select_related(\"same_table_child\", \"extends\").all()\n\n# simple aggregations\nMyModel.objects.filter(name_in=[\"foo\", \"bar\"]).count()\n\n# raw mongo filter\nMyModel.objects.filter(RawMongoDBQuery({\"name\": \"1\"})).delete()\n```\n\n### Search\nUsing the `prefer_search()` extension of MongoQueryset, we can use the `$search` operator of MongoDB to query,\nif we have search indexes configured on the model.\n\n```python\nMyModel.objects.prefer_search().filter(name=\"foo\").all()\n```\n\nPostgreSQL search vectors map down to MongoDB search indexes, so we can use the same syntax as with PostgreSQL.\n\n```python\nclass MyModel(models.Model):\n    name = models.CharField(max_length=100)\n```\n\n```python\nMyModel.objects.annotate(search=SearchVector('name')).filter(search=SearchQuery('foo')).all()\n```\n\n### Raw Queries\n\n```python\nwith connections[\"mongodb\"].cursor() as cursor:\n    doc = cursor.collections[\"my_collection\"].find_one()\n    assert isinstance(doc[\"_id\"], ObjectId)\n```\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fparcellab%2Fdjango-mongo-backend","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Fparcellab%2Fdjango-mongo-backend","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Fparcellab%2Fdjango-mongo-backend/lists"}