Insert documents into MongoDB
Insert a Single Document
Inserting documents into MongoDB can be done using either the save() or create() methods.
Use save() when there is a need to fill the model fields at separate parts of the code.
models.py
from djongo import models
class Entry(models.Model):
_id = models.ObjectIdField()
headline = models.CharField(max_length=255)
Then, in myapp/management/commands/main.py write:
main.py
from django.core.management.base import BaseCommand
from models import Entry
class Command(BaseCommand):
help = "Main execution file"
def handle(self, *args, **options):
entry = Entry(headline='h1')
entry.save()
self.stdout.write(self.style.SUCCESS('Main executed'))
Next, in the command line execute:
python manage.py main
This generates the following pymongo command:
db['myapp_entry'].insert_many(
[{'headline': 'h1'}],
ordered=False)
This can be further shortened using the create() method.
main.py
from django.core.management.base import BaseCommand
from models import Entry
class Command(BaseCommand):
help = "Main execution file"
def handle(self, *args, **options):
entry = Entry.objects.create(headline='h2')
self.stdout.write(self.style.SUCCESS('Main executed'))
EmbeddedField
MongoDB allows the creation of an embedded document. You can include another model in the parent model through the EmbeddedField.
models.py
from djongo import models
class Blog(models.Model):
name = models.CharField(max_length=100)
content = models.TextField()
class Meta:
abstract = True
class Entry(models.Model):
_id = models.ObjectIdField()
blog = models.EmbeddedField(
model_container=Blog
)
headline = models.CharField(max_length=255)
Describe the contents of the EmbeddedField using a dict.
main.py
from django.core.management.base import BaseCommand
from models import Entry
class Command(BaseCommand):
help = "Main execution file"
def handle(self, *args, **options):
entry = Entry.objects.create(
headline='h1',
blog={ 'name': 'Paul', 'content': 'How to sing' }
)
Field data integrity checks
Djongo automatically validates the value assigned to an EmbeddedField.
Integrity criteria (null=True or blank=False) can be applied on the ÈmbeddedField
or to the internal fields (CharField)
models.py
from djongo import models
class Entry(models.Model):
_id = models.ObjectIdField()
blog = models.EmbeddedField(
model_container=Blog,
null=True
)
headline = models.CharField(max_length=255)
main.py
from django.core.management.base import BaseCommand
from models import Entry
class Command(BaseCommand):
help = "Main execution file"
def handle(self, *args, **options):
e = Entry(headline='h1', blog=None)
e.clean_fields()
$ python manage.py main
Works perfectly with no validation errors. Next, set null=False under the EmbeddedField:
models.py
from djongo import models
class Entry(models.Model):
_id = models.ObjectIdField()
blog = models.EmbeddedField(
model_container=Blog,
null=False
)
headline = models.CharField(max_length=255)
main.py
from django.core.management.base import BaseCommand
from models import Entry
class Command(BaseCommand):
help = "Main execution file"
def handle(self, *args, **options):
e = Entry(headline='h1', blog=None)
e.clean_fields()
$ python manage.py main
ValidationError({'blog': ['This field cannot be null.']})
Nesting Embedded Fields
An EmbeddedField or ArrayField can be nested inside an EmbeddedField.
models.py
from djongo import models
class Tagline(models.Model):
title = models.CharField(max_length=100)
subtitle = models.CharField(max_length=100)
class Meta:
abstract = True
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.EmbeddedField(model_container=Tagline)
class Meta:
abstract = True
class Entry(models.Model):
_id = models.ObjectIdField()
blog = models.EmbeddedField(
model_container=Blog
)
headline = models.CharField(max_length=255)
main.py
from django.core.management.base import BaseCommand
from models import Entry
class Command(BaseCommand):
help = "Main execution file"
def handle(self, *args, **options):
e = Entry.objects.create(
headline='h1',
blog={
'name': 'b1',
'tagline': {
'title': 'Tagline Title',
'subtitle': 'Tagline Subtitle'
}
})
Array fields
A model with an ArrayField is created as follows:
models.py
from djongo import models
from django import forms
class Author(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField()
class Meta:
abstract = True
class Entry(models.Model):
headline = models.CharField(max_length=255)
authors = models.ArrayField(
model_container=Author,
)
main.py
from django.core.management.base import BaseCommand
from models import Entry
class Command(BaseCommand):
help = "Main execution file"
def handle(self, *args, **options):
entry = Entry(headline='h1')
entry.authors = [{'name': 'John', 'email': 'john@mail.com'},
{'name': 'Paul', 'email': 'paul@mail.com'}]
entry.save()
