Model Creation

Schema Validation and CheckConstraint

Djongo automatically generates schema validation JSON documents for your models providing an extra layer of data validation and checking from within MongoDB. By creating check constraints in the Model Meta definition, djongo automatically interprets it to generate a JSON Schema and a query expression

Example

from djongo.models import CheckConstraint, Q
from djongo import models
from pymongo.read_concern import ReadConcern

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()
    author_age = models.IntegerField()

    class Meta:
        constraints = [
             CheckConstraint(check=Q(author_age__gte=18), name='age_gte_18')
        ]
copy code

CollectionConstraint and Capped Collections

Djongo introduces a new CollectionConstraint. Use this to specify MongoDB specific collection properties that are usually used when calling create_collection

class CollectionConstraint(**kwargs)
copy code

All arguments passed to create_collection with the exception of name can be used to create the CollectionConstraint instance. Valid arguments include, but are not limited to those described below

Arguments

ArgumentTypeDescription
codec_optionsCodecOptionsAn instance of CodecOptions.
collationCollationTakes an instance of Collation

Example

from djongo.models import CollectionConstraint
from djongo import models
from pymongo.read_concern import ReadConcern

class Blog(models.Model):
    name = models.CharField(max_length=100)
    tagline = models.TextField()

    class Meta:
        constraints = [
            CollectionConstraint(
                read_concern=ReadConcern(level='majority'),
                capped=True,
                max=100
            )
        ]
copy code