Join us Sept 17 at .local NYC! Use code WEB50 to save 50% on tickets. Learn more >
MongoDB Event
Docs Menu
Docs Home
/ / /
Django MongoDB Backend
/

Create Models

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.

This section describes Django MongoDB Backend's support for the following fields, which you can include in your models:

The following table describes the Django model fields that Django MongoDB Backend supports:

Field Type
Description

BigIntegerField

Stores IntegerField values up to 64 bits in size.

BinaryField

Stores raw binary data.

BooleanField

Stores boolean (True or False) values.

CharField

Stores string values. To store longer text values, use TextField.

DateField

Stores date values in Python datetime.date instances.

DateTimeField

Stores date and time values in Python datetime.datetime instances.

DecimalField

Stores decimal values.

DurationField

Stores values representing periods of time in Python timedelta instances.

EmailField

Stores CharField values and uses an EmailValidator to verify that the value is an email address.

FileField

Stores file values.

FilePathField

Stores CharField values that represent filenames on your filesystem.

FloatField

Stores float values.

GenericIPAddressField

Stores an IPv4 or IPv6 address in string format.

ImageField

Stores a FileField value and verifies that the uploaded object is a valid image.

IntegerField

Stores integer values up to 32 bits in size.

JSONField

Stores JSON data. To learn more about this field, see the Store JSON Data section in this guide.

PositiveBigIntegerField

Stores positive integer values up to 64 bits in size.

PositiveIntegerField

Stores positive integer values up to 32 bits in size.

PositiveSmallIntegerField

Stores positive integer values up to 16 bits in size.

SlugField

Stores a short text label, often for URL values.

SmallIntegerField

Stores integer values up to 16 bits in size.

TextField

Stores large text values.

URLField

Stores a CharField value representing a URL.

UUIDField

Stores instances of Python's UUID class.

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

Array

ArrayField

Stores array values. To learn more about using this field with Django MongoDB Backend, see the Store Array Data section in this guide.

Object

EmbeddedModelField or EmbeddedModelArrayField

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.

ObjectId

ObjectIdField

Stores unique 12-byte identifiers that MongoDB uses as primary keys.

Binary

BinaryField

Stores binary data.

Boolean

BooleanField

Stores true or false values.

Date

DatetimeField

Stores dates and times in milliseconds since the Unix epoch, or January 1, 1970.

Decimal128

DecimalField

Stores 28-bit decimal values.

Double

FloatField

Stores floating-point values.

Int32

IntegerField

Stores 32-bit signed integers.

Int64

IntegerField or BigIntegerField

Stores 64-bit signed integers.

String

CharField or TextField

Stores UTF-8 encoded string values.

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

This sample models.py file defines a Movie model class that includes the following information:

  • List of fields that represent movie data.

  • Meta class that sets the db_table option to movies. This instructs Django MongoDB Backend to use this model to represent the sample_mflix.movies collection from the Atlas sample datasets.

    The Meta class also sets the managed option to False, instructing Django MongoDB Backend not to create a new collection for the model.

  • __str__() method that defines the model's string representation as its title field 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.

This section shows how to use the following fields in your Django models:

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.

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.

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 SQL NULL value. Alternatively, you can set the JSONField value to Value(None, JSONField()), which represents the JSON scalar null. However, there is no way to distinguish between the SQL NULL and the JSON null when querying.

  • Some queries that use Q objects might not return the expected results, particularly when using the QuerySet.exclude() method.

  • When querying for fields that have a None value, Django MongoDB Backend incorrectly returns documents in which the field doesn't exist.

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 specify EmbeddedModelField or FileField as 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
),
)

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.

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.

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.

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.

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

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.

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.

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 store

  • max_size: (Optional) Specifies the maximum size of the array

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.

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.

Back

Create Indexes

On this page