Skip to main content

DocumentDB/MongoDB backend for Django

Project description

DocumentDB/MongoDB backend for Django

This backend is in currently in development and is not advised for Production workflows. Backwards incompatible changes may be made without notice. We welcome your feedback as we continue to explore and build. The best way to share this is via our MongoDB Community Forum

Install and usage

pip install django-documentdb

Specifying the default primary key field

In your Django settings, you must specify that all models should use ObjectIdAutoField.

You can create a new project that's configured based on these steps using a project template:

$ django-admin startproject mysite --template https://github.com/mongodb-labs/django-mongodb-project/archive/refs/heads/5.0.x.zip

(where "5.0" matches the version of Django that you're using.)

This template includes the following line in settings.py:

DEFAULT_AUTO_FIELD = "django_documentdb.fields.ObjectIdAutoField"

But this setting won't override any apps that have an AppConfig that specifies default_auto_field. For those apps, you'll need to create a custom AppConfig.

For example, the project template includes <project_name>/apps.py:

from django.contrib.admin.apps import AdminConfig
from django.contrib.auth.apps import AuthConfig
from django.contrib.contenttypes.apps import ContentTypesConfig


class MongoAdminConfig(AdminConfig):
    default_auto_field = "django_documentdb.fields.ObjectIdAutoField"


class MongoAuthConfig(AuthConfig):
    default_auto_field = "django_documentdb.fields.ObjectIdAutoField"


class MongoContentTypesConfig(ContentTypesConfig):
    default_auto_field = "django_documentdb.fields.ObjectIdAutoField"

Each app reference in the INSTALLED_APPS setting must point to the corresponding AppConfig. For example, instead of 'django.contrib.admin', the template uses '<project_name>.apps.MongoAdminConfig'.

Configuring migrations

Because all models must use ObjectIdAutoField, each third-party and contrib app you use needs to have its own migrations specific to MongoDB.

For example, settings.py in the project template specifies:

MIGRATION_MODULES = {
    "admin": "mongo_migrations.admin",
    "auth": "mongo_migrations.auth",
    "contenttypes": "mongo_migrations.contenttypes",
}

The project template includes these migrations, but you can generate them if you're setting things up manually or if you need to create migrations for third-party apps. For example:

$ python manage.py makemigrations admin auth contenttypes
Migrations for 'admin':
  mongo_migrations/admin/0001_initial.py
    - Create model LogEntry
...

Creating Django applications

Whenever you run python manage.py startapp, you must remove the line:

default_auto_field = 'django.db.models.BigAutoField'

from the new application's apps.py file (or change it to reference "django_mongodb.fields.ObjectIdAutoField").

Alternatively, you can use the following startapp template which includes this change:

$ python manage.py startapp myapp --template https://github.com/mongodb-labs/django-mongodb-app/archive/refs/heads/5.0.x.zip

(where "5.0" matches the version of Django that you're using.)

Configuring the DATABASES setting

After you've set up a project, configure Django's DATABASES setting similar to this:

DATABASES = {
    "default": {
        "ENGINE": "django_documentdb",
        "NAME": "my_database",
        "USER": "my_user",
        "PASSWORD": "my_password",
        "OPTIONS": {...},
    },
}

OPTIONS is an optional dictionary of parameters that will be passed to MongoClient.

Congratulations, your project is ready to go!

Notes on Django QuerySets

django-documentdb uses own QuerySet implementation (DocumentQuerySet) if you inherit your models from DocumentModel class.

Example:

from django_documentdb.models import DocumentModel
from django_documentdb import fields
from django.db import models


class TestModel(DocumentModel):
    _id = fields.ObjectIdAutoField(primary_key=True)
    text_value = models.CharField(max_length=100, null=True)
    number_value = models.FloatField(null=True)

    class Meta:
        db_table = "test_db"
        use_mongodb = True

Available options with DocumentQuerySet:

  • QuerySet.explain() supports the comment and verbosity options.

    Example: QuerySet.explain(comment="...", verbosity="...")

    Valid values for verbosity are "queryPlanner" (default), "executionStats", and "allPlansExecution".

  • DocumentQuerySet.index_hint(index_name) - allows to specify index hint for query.

Known issues and limitations

  • The following QuerySet methods aren't supported:

    • bulk_update()
    • dates()
    • datetimes()
    • distinct()
    • extra()
    • prefetch_related()
  • QuerySet.delete() and update() do not support queries that span multiple collections.

  • DateTimeField doesn't support microsecond precision, and correspondingly, DurationField stores milliseconds rather than microseconds.

  • The following database functions aren't supported:

    • Chr
    • ExtractQuarter
    • MD5
    • Now
    • Ord
    • Pad
    • Repeat
    • Reverse
    • Right
    • SHA1, SHA224, SHA256, SHA384, SHA512
    • Sign
    • TruncDate
    • TruncTime
  • The tzinfo parameter of the Trunc database functions doesn't work properly because MongoDB converts the result back to UTC.

  • When querying JSONField:

    • There is no way to distinguish between a JSON "null" (represented by Value(None, JSONField())) and a SQL null (queried using the isnull lookup). Both of these queries return both of these nulls.
    • Some queries with Q objects, e.g. Q(value__foo="bar"), don't work properly, particularly with QuerySet.exclude().
    • Filtering for a None key, e.g. QuerySet.filter(value__j=None) incorrectly returns objects where the key doesn't exist.
    • You can study the skipped tests in DatabaseFeatures.django_test_skips for more details on known issues.
  • Due to the lack of ability to introspect MongoDB collection schema, migrate --fake-initial isn't supported.

Forked Project

This project, django-documentdb, is a fork of the original django-mongodb library, which aimed to integrate MongoDB with Django. The fork was created to enhance compatibility with AWS DocumentDB, addressing the limitations of its API support while maintaining the core functionalities of the original library. We appreciate the work of the MongoDB Python Team and aim to build upon their foundation to better serve users needing DocumentDB integration.

Project details


Download files

Download the file for your platform. If you're not sure which to choose, learn more about installing packages.

Source Distribution

django_documentdb-0.0.1.tar.gz (52.9 kB view details)

Uploaded Source

Built Distribution

django_documentdb-0.0.1-py3-none-any.whl (55.4 kB view details)

Uploaded Python 3

File details

Details for the file django_documentdb-0.0.1.tar.gz.

File metadata

  • Download URL: django_documentdb-0.0.1.tar.gz
  • Upload date:
  • Size: 52.9 kB
  • Tags: Source
  • Uploaded using Trusted Publishing? Yes
  • Uploaded via: twine/5.1.1 CPython/3.12.7

File hashes

Hashes for django_documentdb-0.0.1.tar.gz
Algorithm Hash digest
SHA256 616616b7d9d3d480335465b650c17f99eb50ee395544d29831f892bab4826e5a
MD5 64fc239e9bf9578d2a6b44f41b08bae5
BLAKE2b-256 253ce2e8138ee2b970f5e9770c0711d8e6e6c1ce4299aec02884545eb30bf8aa

See more details on using hashes here.

File details

Details for the file django_documentdb-0.0.1-py3-none-any.whl.

File metadata

File hashes

Hashes for django_documentdb-0.0.1-py3-none-any.whl
Algorithm Hash digest
SHA256 563b6f03c0648a31f042e7bc5bf0ef5089d34d5f02beadf4b0b5ddb6f70cff0a
MD5 25a73ac3f5f2d526ddf3a1623fab2dbc
BLAKE2b-256 75ee1106f5d24ae50797311c4dd32a69940bf82c848fc93a0f973e62f1d2e9d6

See more details on using hashes here.

Supported by

AWS AWS Cloud computing and Security Sponsor Datadog Datadog Monitoring Fastly Fastly CDN Google Google Download Analytics Microsoft Microsoft PSF Sponsor Pingdom Pingdom Monitoring Sentry Sentry Error logging StatusPage StatusPage Status page