Create Models
On this page
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 Field Types
This section describes Django MongoDB Backend's support for the following field types, 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 IntegerField values up to 64 bits in size. |
| Stores raw binary data. |
| Stores boolean ( True or False ) values. |
| Stores string values. To store longer text values, use
TextField . |
| Stores date values in Python datetime.date instances. |
| Stores date and time values in Python datetime.datetime
instances. |
| Stores decimal values. |
| Stores values representing periods of time in
Python timedelta instances. |
| Stores CharField values and uses an EmailValidator
to verify that the value is an email address. |
| Stores file values. |
| Stores CharField values that represent filenames on your filesystem. |
| Stores float values. |
| Stores an IPv4 or IPv6 address in string format. |
| Stores a FileField value and verifies that the uploaded object
is a valid image. |
| Stores integer values up to 32 bits in size. |
| Stores JSON data. To learn more about this field, see the
Use a JSONField 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 positive integer values up to 16 bits in size. |
| Stores a short text label, often for URL values. |
| Stores integer values up to 16 bits in size. |
| Stores large text values. |
| Stores a CharField value representing a URL. |
| Stores instances of Python's UUID class. |
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 Use an ArrayField section
in this guide. |
|
| Stores embedded documents. To learn more about using this field
with Django MongoDB Backend, see the Use an EmbeddedModelField section in this guide. |
|
| Stores unique 12-byte identifiers that MongoDB uses as primary keys. |
|
| Stores binary data. |
|
| Stores true or false values. |
|
| 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.
Meta
class that sets thedb_table
option tomovies
. This instructs Django MongoDB Backend to use this model to represent thesample_mflix.movies
collection from the Atlas sample datasets.The
Meta
class also sets themanaged
option toFalse
, instructing Django MongoDB Backend not to create a new collection for the model.__str__()
method that defines the model's string representation as itstitle
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 field types used in the model class definition, see the Supported Field Types section of this guide.
Use Advanced Fields
This section shows how to use the following field types in your Django models:
Use a JSONField
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 an EmbeddedModelField
to represent a
MongoDB Object
. To learn more about this field, see the
Use an EmbeddedModelField section of this guide.
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 a JSONField 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 SQLNULL
value. Alternatively, you can set theJSONField
value toValue(None, JSONField())
, which represents the JSON scalarnull
. However, there is no way to distinguish between the SQLNULL
and the JSONnull
when querying.Some queries that use
Q
objects might not return the expected results, particularly when using theQuerySet.exclude()
method.When querying for fields that have a
None
value, Django MongoDB Backend incorrectly returns documents in which the field doesn't exist.
Use an ArrayField
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 specifyEmbeddedModelField
orFileField
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
.
To view an example of a multi-dimensional array, see ArrayField in the Django
PostgreSQL documentation.
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 an ArrayField in the Specify a Query guide.
Use an EmbeddedModelField
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 an EmbeddedModelField 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 field types, see the Model field reference in the Django documentation.