mongodb-labs / django-mongodb

MongoDB Backend for Django
Apache License 2.0
2 stars 5 forks source link

MongoDB backend for Django

This backend is in the pre-alpha stage of development. Backwards incompatible changes may be made without notice. We welcome your feedback as we continue to explore and build.

Install and usage

The development version of this package supports Django 5.0.x. To install it:

pip install git+https://github.com/mongodb-labs/django-mongodb

Configure the Django DATABASES setting similar to this:

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

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

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

DEFAULT_AUTO_FIELD = "django_mongodb.fields.ObjectIdAutoField"

This 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, you might create mysite/apps.py like this:

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_mongodb.fields.ObjectIdAutoField"

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

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

Then replace each app reference in the INSTALLED_APPS setting with the new AppConfig. For example, replace 'django.contrib.admin' with 'mysite.apps.MongoAdminConfig'.

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, you might configure your settings like this:

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

After creating a mongo_migrations directory, you can then run:

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

And 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.

Notes on Django QuerySets

Known issues and limitations

Troubleshooting

TODO