Model field reference¶
Supported model fields¶
All of Django’s model fields are supported, except:
AutoField(includingBigAutoFieldandSmallAutoField)
A few notes about some of the other fields:
DateTimeFieldis limited to millisecond precision (rather than microsecond like most other databases), and correspondingly,DurationFieldstores milliseconds rather than microseconds.SmallIntegerFieldandPositiveSmallIntegerFieldsupport 32 bit values (ranges(-2147483648, 2147483647)and(0, 2147483647), respectively), validated by forms and model validation. Be careful because MongoDB doesn’t prohibit inserting values outside of the supported range and unique constraints don’t work for values outside of the 32-bit range of the BSONinttype.IntegerField,BigIntegerFieldandPositiveSmallIntegerField, andPositiveBigIntegerFieldsupport 64 bit values (ranges(-9223372036854775808, 9223372036854775807)and(0, 9223372036854775807), respectively), validated by forms and model validation. If you’re inserting data outside of the ORM, you must cast all values tobson.int64.Int64, otherwise values less then 32 bits will be stored asintand won’t be validated by unique constraints.Similarly, all
DurationFieldvalues are stored asbson.int64.Int64.
Model field options¶
Some notes about model field options:
Dollar signs and periods (
$and.) are not supported inField.db_columnbecause these field names are discouraged by MongoDB. Querying fields with these characters requires the$getFieldoperator, which prevents queries from using indexes.
MongoDB-specific model fields¶
Some MongoDB-specific fields are available in django_mongodb_backend.fields.
ArrayField¶
- class ArrayField(base_field, max_size=None, size=None, **options)¶
A field for storing lists of data. Most field types can be used, and you pass another field instance as the
base_field. You may also specify asizeormax_size.ArrayFieldcan be nested to store multi-dimensional arrays.If you give the field a
default, ensure it’s a callable such aslist(for an empty default) or a callable that returns a list (such as a function). Incorrectly usingdefault=[]creates a mutable default that is shared between all instances ofArrayField.- base_field¶
This is a required argument.
Specifies the underlying data type and behavior for the array. It should be an instance of a subclass of
Field. For example, it could be anIntegerFieldor aCharField. Most field types are permitted, with the exception of those handling relational data (ForeignKey,OneToOneFieldandManyToManyField) and file fields (FileFieldandImageField). ForEmbeddedModelField, useEmbeddedModelArrayField.It is possible to nest array fields - you can specify an instance of
ArrayFieldas thebase_field. For example:from django.db import models from django_mongodb_backend.fields import ArrayField class ChessBoard(models.Model): board = ArrayField( ArrayField( models.CharField(max_length=10, blank=True), size=8, ), size=8, )
Transformation of values between the database and the model, validation of data and configuration, and serialization are all delegated to the underlying base field.
- max_size¶
This is an optional argument.
If passed, the array will have a maximum size as specified, validated by forms and model validation, but not enforced by the database.
The
max_sizeandsizeoptions are mutually exclusive.
- size¶
This is an optional argument.
If passed, the array will have size as specified, validated by forms and model validation, but not enforced by the database.
Querying ArrayField¶
There are a number of custom lookups and transforms for ArrayField.
We will use the following example model:
from django.db import models
from django_mongodb_backend.fields import ArrayField
class Post(models.Model):
name = models.CharField(max_length=200)
tags = ArrayField(models.CharField(max_length=200), blank=True)
def __str__(self):
return self.name
contains¶
The contains lookup is overridden on ArrayField. The
returned objects will be those where the values passed are a subset of the
data. It uses the $setIntersection operator. For example:
>>> Post.objects.create(name="First post", tags=["thoughts", "django"])
>>> Post.objects.create(name="Second post", tags=["thoughts"])
>>> Post.objects.create(name="Third post", tags=["tutorial", "django"])
>>> Post.objects.filter(tags__contains=["thoughts"])
<QuerySet [<Post: First post>, <Post: Second post>]>
>>> Post.objects.filter(tags__contains=["django"])
<QuerySet [<Post: First post>, <Post: Third post>]>
>>> Post.objects.filter(tags__contains=["django", "thoughts"])
<QuerySet [<Post: First post>]>
contained_by¶
This is the inverse of the contains lookup -
the objects returned will be those where the data is a subset of the values
passed. It uses the $setIntersection operator. For example:
>>> Post.objects.create(name="First post", tags=["thoughts", "django"])
>>> Post.objects.create(name="Second post", tags=["thoughts"])
>>> Post.objects.create(name="Third post", tags=["tutorial", "django"])
>>> Post.objects.filter(tags__contained_by=["thoughts", "django"])
<QuerySet [<Post: First post>, <Post: Second post>]>
>>> Post.objects.filter(tags__contained_by=["thoughts", "django", "tutorial"])
<QuerySet [<Post: First post>, <Post: Second post>, <Post: Third post>]>
overlap¶
Returns objects where the data shares any results with the values passed. It
uses the $setIntersection operator. For example:
>>> Post.objects.create(name="First post", tags=["thoughts", "django"])
>>> Post.objects.create(name="Second post", tags=["thoughts", "tutorial"])
>>> Post.objects.create(name="Third post", tags=["tutorial", "django"])
>>> Post.objects.filter(tags__overlap=["thoughts"])
<QuerySet [<Post: First post>, <Post: Second post>]>
>>> Post.objects.filter(tags__overlap=["thoughts", "tutorial"])
<QuerySet [<Post: First post>, <Post: Second post>, <Post: Third post>]>
len¶
Returns the length of the array. The lookups available afterward are those
available for IntegerField. For example:
>>> Post.objects.create(name="First post", tags=["thoughts", "django"])
>>> Post.objects.create(name="Second post", tags=["thoughts"])
>>> Post.objects.filter(tags__len=1)
<QuerySet [<Post: Second post>]>
Index transforms¶
Index transforms index into the array. Any non-negative integer can be used.
There are no errors if it exceeds the max_size of the
array. The lookups available after the transform are those from the
base_field. For example:
>>> Post.objects.create(name="First post", tags=["thoughts", "django"])
>>> Post.objects.create(name="Second post", tags=["thoughts"])
>>> Post.objects.filter(tags__0="thoughts")
<QuerySet [<Post: First post>, <Post: Second post>]>
>>> Post.objects.filter(tags__1__iexact="Django")
<QuerySet [<Post: First post>]>
>>> Post.objects.filter(tags__276="javascript")
<QuerySet []>
These indexes use 0-based indexing.
Slice transforms¶
Slice transforms take a slice of the array. Any two non-negative integers can be used, separated by a single underscore. The lookups available after the transform do not change. For example:
>>> Post.objects.create(name="First post", tags=["thoughts", "django"])
>>> Post.objects.create(name="Second post", tags=["thoughts"])
>>> Post.objects.create(name="Third post", tags=["django", "python", "thoughts"])
>>> Post.objects.filter(tags__0_1=["thoughts"])
<QuerySet [<Post: First post>, <Post: Second post>]>
>>> Post.objects.filter(tags__0_2__contains=["thoughts"])
<QuerySet [<Post: First post>, <Post: Second post>]>
These indexes use 0-based indexing.
EmbeddedModelField¶
- class EmbeddedModelField(embedded_model, **kwargs)¶
Stores a model of type
embedded_model.- embedded_model¶
This is a required argument.
Specifies the model class to embed. It must be a subclass of
django_mongodb_backend.models.EmbeddedModel.It can be either a concrete model class or a lazy reference to a model class.
The embedded model cannot have relational fields (
ForeignKey,OneToOneFieldandManyToManyField).It is possible to nest embedded models. For example:
from django.db import models from django_mongodb_backend.fields import EmbeddedModelField from django_mongodb_backend.models import EmbeddedModel class Address(EmbeddedModel): ... class Author(EmbeddedModel): address = EmbeddedModelField(Address) class Book(models.Model): author = EmbeddedModelField(Author)
See the embedded model topic guide for more details and examples.
Migrations support is limited
makemigrations does not yet detect changes to embedded models.
After you create a model with an EmbeddedModelField or add an
EmbeddedModelField to an existing model, no further updates to the
embedded model will be made. Using the models above as an example, if you
created these models and then added an indexed field to Address,
the index created in the nested Book embed is not created.
EmbeddedModelArrayField¶
- class EmbeddedModelArrayField(embedded_model, max_size=None, **kwargs)¶
Similar to
EmbeddedModelField, but stores a list of models of typeembedded_modelrather than a single instance.- embedded_model¶
This is a required argument that works just like
EmbeddedModelField.embedded_model.
- max_size¶
This is an optional argument.
If passed, the list will have a maximum size as specified, validated by forms and model validation, but not enforced by the database.
See the embedded model topic guide for more details and examples.
Migrations support is limited
As described above for EmbeddedModelField,
makemigrations does not yet detect changes to embedded models.
ObjectIdAutoField¶
- class ObjectIdAutoField¶
This field is typically the default primary key field for all models stored in MongoDB. See Specifying the default primary key field.
ObjectIdField¶
PolymorphicEmbeddedModelField¶
- class PolymorphicEmbeddedModelField(embedded_models, **kwargs)¶
Stores a model of one of the types in
embedded_models.- embedded_models¶
This is a required argument that specifies a list of model classes that may be embedded.
Each model class reference works just like
EmbeddedModelField.embedded_model.
See the embedded model topic guide for more details and examples.
Migrations support is limited
makemigrations does not yet detect changes to embedded models,
nor does it create indexes or constraints for embedded models referenced
by PolymorphicEmbeddedModelField.
Forms are not supported
PolymorphicEmbeddedModelFields don’t appear in model forms.
PolymorphicEmbeddedModelArrayField¶
- class PolymorphicEmbeddedModelArrayField(embedded_models, **kwargs)¶
Similar to
PolymorphicEmbeddedModelField, but stores a list of models of typeembedded_modelsrather than a single instance.- embedded_models¶
This is a required argument that works just like
PolymorphicEmbeddedModelField.embedded_models.
- max_size¶
This is an optional argument.
If passed, the list will have a maximum size as specified, validated by forms and model validation, but not enforced by the database.
See the embedded model topic guide for more details and examples.
Migrations support is limited
makemigrations does not yet detect changes to embedded models,
nor does it create indexes or constraints for embedded models referenced
by PolymorphicEmbeddedModelArrayField.
Forms are not supported
PolymorphicEmbeddedModelArrayFields don’t appear in model forms.