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.
TipTo learn more about Django models, see Model
in the Django documentation.
This section describes Django MongoDB Backend's support for the following field types, 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
Use a JSONFieldsection 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.
TipTo 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
Use an ArrayFieldsection 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
Use an EmbeddedModelFieldand
Use an EmbeddedModelArrayFieldsections.
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> class Meta: def __str__(self):
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>', ]
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 modelsclass 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.
This section shows how to use the following field types 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.
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.
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 modelsclass 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.
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.
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.
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 modelsfrom django_mongodb_backend.fields import ArrayFieldclass 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.
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.
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 modelsfrom django_mongodb_backend.models import EmbeddedModelfrom django_mongodb_backend.fields import EmbeddedModelFieldclass 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
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 modelsfrom django_mongodb_backend.models import EmbeddedModelfrom django_mongodb_backend.fields import EmbeddedModelArrayFieldclass 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
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.
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4