Overview
In this guide, you can learn how to create Django models that represent MongoDB collections. Models are Python classes that define the structure of your data. When using Django MongoDB Backend, you can map each model to a MongoDB collection and interact with the collection's documents by using model objects.
Tip
To learn more about Django models, see Model in the Django documentation.
Supported Fields
This section describes Django MongoDB Backend's support for the following fields, which you can include in your models:
Django Fields
The following table describes the Django model fields that Django MongoDB Backend supports:
Field Type | Description |
|---|---|
| Stores raw binary data. |
| Stores boolean ( |
| Stores string values. To store longer text values, use
|
| Stores date values in Python |
| Stores date and time values in Python |
| Stores decimal values. |
| Stores values representing periods of time in
Python |
| Stores |
| Stores file values. |
| Stores |
| Stores float values. |
| Stores an IPv4 or IPv6 address in string format. |
| Stores a |
| Stores integer values up to 64 bits in size. |
| Stores JSON data. To learn more about this field, see the Store JSON Data section in this guide. |
| Stores positive integer values up to 64 bits in size. |
| Stores positive integer values up to 32 bits in size. |
| Stores a short text label, often for URL values. |
| Stores integer values up to 32 bits in size. |
| Stores large text values. |
| Stores a |
| Stores instances of Python's |
MongoDB BSON Fields
MongoDB organizes and stores documents in a binary representation called BSON that allows for flexible data processing.
Tip
To learn more about how MongoDB stores BSON data, see BSON Types in the MongoDB Server manual.
The following table describes supported BSON field types and their Django MongoDB Backend equivalents that you can use in your Django models:
BSON Field Type | Django MongoDB Backend Field Type | BSON Description |
|---|---|---|
|
| Stores array values. To learn more about using this field with Django MongoDB Backend, see the Store Array Data section in this guide. |
|
| Stores one or multiple embedded documents. To learn more about using these fields with Django MongoDB Backend, see the Store Embedded Model Data and Store Embedded Model Array Data sections. |
|
| Stores unique 12-byte identifiers that MongoDB uses as primary keys. |
|
| Stores binary data. |
|
| Stores |
|
| Stores dates and times in milliseconds since the Unix epoch, or January 1, 1970. |
|
| Stores 28-bit decimal values. |
|
| Stores floating-point values. |
|
| Stores 32-bit signed integers. |
|
| Stores 64-bit signed integers. |
|
| Stores UTF-8 encoded string values. |
Define a Model
To create a model that represents a MongoDB collection, add your model class definitions to your application's models.py file. In your model class, specify the fields you want to store and include any model metadata in an inner Meta class. You can also use the __str__() method to define the string representation of your model. Use the following syntax to define a model:
class <Model name>(models.Model): <field name> = <data type> # Include additional fields here class Meta: # Include metadata here def __str__(self): # Include logic for displaying your model as a string here
Tip
To learn more about the metadata options you can specify in the Meta class, see Model Meta options in the Django documentation.
To use your models, you must add them to your project's settings.py file. Edit the INSTALLED_APPS value to include the name of the module that stores your models.py file, as shown in the following code:
INSTALLED_APPS = [ '<application module>', # Include other app modules here ]
Finally, run the following database migration commands from your project's root directory to create MongoDB collections for your models or use existing collections to store model data:
python manage.py makemigrations <application name> python manage.py migrate
Example
This sample models.py file defines a Movie model class that includes the following information:
List of fields that represent movie data.
Metaclass that sets thedb_tableoption tomovies. This instructs Django MongoDB Backend to use this model to represent thesample_mflix.moviescollection from the Atlas sample datasets.The
Metaclass also sets themanagedoption toFalse, instructing Django MongoDB Backend not to create a new collection for the model.__str__()method that defines the model's string representation as itstitlefield value.
from django.db import models class Movie(models.Model): title = models.CharField(max_length=200) plot = models.TextField(blank=True) runtime = models.IntegerField(default=0) released = models.DateTimeField("release date", null=True, blank=True) class Meta: db_table = "movies" managed = False def __str__(self): return self.title
Tip
To learn more about the fields used in the model class definition, see the Supported Fields section of this guide.
Use Advanced Fields
This section shows how to use the following fields in your Django models:
Store JSON Data
You can use a JSONField in your model to store JSON objects. JSON is a human-readable format for data exchange, and JSON objects are data containers that map string keys to values. MongoDB provides the Object field type to store JSON data in documents and internally stores this data in BSON, or Binary JSON, format.
Note
You can also use embedded models and polymorphic embedded models to represent a MongoDB Object.
Example
The following example adds a JSONField value to the model created in the Define a Model example in this guide. The new field, called imdb, stores JSON data that represents user ratings for each Movie object:
from django.db import models class Movie(models.Model): title = models.CharField(max_length=200) plot = models.TextField(blank=True) runtime = models.IntegerField(default=0) released = models.DateTimeField("release date", null=True, blank=True) imdb = models.JSONField(null=True, blank=True) class Meta: db_table = "movies" managed = False def __str__(self): return self.title
Tip
To learn how to query data stored in a JSONField, see Query JSON Values in the Specify a Query guide.
Limitations
Django MongoDB Backend's support for JSONField has the following limitations:
If you set the field's value to
None, Django MongoDB Backend stores its value as a SQLNULLvalue. Alternatively, you can set theJSONFieldvalue toValue(None, JSONField()), which represents the JSON scalarnull. However, there is no way to distinguish between the SQLNULLand the JSONnullwhen querying.Some queries that use
Qobjects might not return the expected results, particularly when using theQuerySet.exclude()method.When querying for fields that have a
Nonevalue, Django MongoDB Backend incorrectly returns documents in which the field doesn't exist.
Store Array Data
You can use an ArrayField in your model to store a list of data. To create an ArrayField, use the ArrayField() class constructor and pass the following arguments:
base_field: Specifies the underlying data type of each value stored in the array. You cannot specifyEmbeddedModelFieldorFileFieldas the base field type.size: (Optional) Specifies the maximum size of the array.options: (Optional) Specifies Django field options. To view a list of available options, see Field options in the Django documentation.
Tip
You can store an array of array values in an ArrayField by using the following syntax:
my_array = ArrayField( ArrayField( base_field, # ... Additional arguments ), )
Example
The following example adds an ArrayField value to the model created in the Define a Model example in this guide. The new field, called genres, stores a list of CharField values that represent movie genres and can store a maximum of 5 values:
from django.db import models from django_mongodb_backend.fields import ArrayField class Movie(models.Model): title = models.CharField(max_length=200) plot = models.TextField(blank=True) runtime = models.IntegerField(default=0) released = models.DateTimeField("release date", null=True, blank=True) genres = ArrayField( models.CharField(max_length=100), size=5, null=True, blank=True) class Meta: db_table = "movies" managed = False def __str__(self): return self.title
Tip
To learn how to query data stored in an ArrayField, see Query Array Values in the Specify a Query guide.
Store Embedded Model Data
You can use an EmbeddedModelField to represent a MongoDB Object, which stores a nested document value. This type allows one model to store a separate model in one of its fields. To create an EmbeddedModelField, define an embedded model class as a subclass of the EmbeddedModel abstract model. Then, create a field in your base model class by using the EmbeddedModelField() constructor and pass the following arguments:
embedded_model: Specifies the model class to store.options: (Optional) Specifies Django field options. To view a list of available options, see Field options in the Django documentation.
Important
The makemigrations Django command does not detect changes to embedded models. If you make changes to the embedded model's class, the model stored in the EmbeddedModelField does not reflect the changes.
Example
This example adds an EmbeddedModelField value to the model created in the Define a Model example in this guide. The new field, called awards, stores an embedded Award model as its value. The following code defines the Award model and modifies the Movie model to include the EmbeddedModelField:
from django.db import models from django_mongodb_backend.models import EmbeddedModel from django_mongodb_backend.fields import EmbeddedModelField class Award(EmbeddedModel): wins = models.IntegerField(default=0) nominations = models.IntegerField(default=0) text = models.CharField(max_length=100) class Movie(models.Model): title = models.CharField(max_length=200) plot = models.TextField(blank=True) runtime = models.IntegerField(default=0) released = models.DateTimeField("release date", null=True, blank=True) awards = EmbeddedModelField(Award, null=True, blank=True) class Meta: db_table = "movies" managed = False def __str__(self): return self.title
Tip
To learn how to query data stored in an EmbeddedModelField, see Query Embedded Model Values in the Specify a Query guide.
Store Embedded Model Array Data
You can use an EmbeddedModelArrayField to represent a MongoDB document field that stores an array of documents in a one-to-many relationship. Each document in the array corresponds to a Django MongoDB Backend EmbeddedModelField value. To create an EmbeddedModelArrayField, use the EmbeddedModelArrayField() class constructor and pass the following arguments:
embedded_model: Specifies the model stored in each array item.max_size: (Optional) Specifies the maximum size of the array.
Example
This example adds an EmbeddedModelArrayField value to the model created in the Define a Model example in this guide. This cast field stores an array of embedded Actor models. The following code defines the Actor model and modifies the Movie model to include the EmbeddedModelArrayField:
from django.db import models from django_mongodb_backend.models import EmbeddedModel from django_mongodb_backend.fields import EmbeddedModelArrayField class Actor(EmbeddedModel): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) role = models.CharField(max_length=100) class Movie(models.Model): title = models.CharField(max_length=200) plot = models.TextField(blank=True) runtime = models.IntegerField(default=0) released = models.DateTimeField("release date", null=True, blank=True) cast = EmbeddedModelArrayField(Actor, null=True, blank=True) class Meta: db_table = "movies" managed = False def __str__(self): return self.title
Store Polymorphic Embedded Model Data
You can use a PolymorphicEmbeddedModelField to represent a MongoDB document field that can store multiple types of embedded documents. Each embedded document is represented by a Django MongoDB Backend model class.
To create a PolymorphicEmbeddedModelField, pass the embedded_models argument to the PolymorphicEmbeddedModelField() class constructor. This argument specifies a list of model classes that the field can store.
Example
This example adds a PolymorphicEmbeddedModelField value to the model created in the Define a Model example in this guide. This awards field can store an embedded model of type Oscars or GoldenGlobes. Each embedded model contains information about all the Oscar or Golden Globe awards a movie has won.
The following code defines the Oscars and GoldenGlobes embedded models, and then modifies the Movie model to include the PolymorphicEmbeddedModelField:
from django.db import models from django_mongodb_backend.models import EmbeddedModel from django_mongodb_backend.fields import PolymorphicEmbeddedModelField class Oscars(EmbeddedModel): wins = models.IntegerField(default=0) nominations = models.IntegerField(default=0) best_picture = models.BooleanField(default=False) class GoldenGlobes(EmbeddedModel): wins = models.IntegerField(default=0) nominations = models.IntegerField(default=0) class Movie(models.Model): title = models.CharField(max_length=200) plot = models.TextField(blank=True) runtime = models.IntegerField(default=0) released = models.DateTimeField("release date", null=True, blank=True) awards = PolymorphicEmbeddedModelField(["Oscars", "GoldenGlobes"], null=True, blank=True) class Meta: db_table = "movies" managed = False def __str__(self): return self.title
Tip
To learn how to query data stored in a PolymorphicEmbeddedModelField, see Query Polymorphic Embedded Model Values in the Specify a Query guide.
Store Polymorphic Embedded Model Array Data
You can use a PolymorphicEmbeddedModelArrayField to represent a MongoDB document field that can store multiple types of embedded documents. This field is similar to the PolymorphicEmbeddedModelField, but it stores an array of embedded documents instead of a single document. Each embedded document in the array is represented by a Django MongoDB Backend model class.
To create a PolymorphicEmbeddedModelArrayField, pass the following arguments to the PolymorphicEmbeddedModelArrayField() class constructor:
embedded_models: Specifies the model classes that the field can storemax_size: (Optional) Specifies the maximum size of the array
Example
This example adds a PolymorphicEmbeddedModelArrayField value to the model created in the Define a Model example in this guide. This awards field can store a list of embedded models of type Oscar or GoldenGlobe. Each embedded model contains information about one Oscar or Golden Globe award that a movie has won.
The following code defines the Oscar and GoldenGlobe embedded models, and then modifies the Movie model to include the PolymorphicEmbeddedModelArrayField:
from django.db import models from django_mongodb_backend.models import EmbeddedModel from django_mongodb_backend.fields import PolymorphicEmbeddedModelArrayField class Oscar(EmbeddedModel): category = models.CharField(max_length=200) year = models.IntegerField(default=0) class GoldenGlobe(EmbeddedModel): category = models.CharField(max_length=200) year = models.IntegerField(default=0) class Movie(models.Model): title = models.CharField(max_length=200) plot = models.TextField(blank=True) runtime = models.IntegerField(default=0) released = models.DateTimeField("release date", null=True, blank=True) awards = PolymorphicEmbeddedModelArrayField(["Oscar", "GoldenGlobe"], null=True, blank=True) class Meta: db_table = "movies" managed = False def __str__(self): return self.title
Tip
To learn how to query data stored in a PolymorphicEmbeddedModelArrayField, see Query Polymorphic Embedded Model Array Values in the Specify a Query guide.
Additional Information
To learn how to use your models to run database operations, see the Interact with Data guides.
To learn more about Django fields, see the Model field reference in the Django documentation.