For AI agents: a documentation index is available at https://www.mongodb.com/docs/llms.txt — markdown versions of all pages are available by appending .md to any URL path.
Docs Menu

Serialize MongoDB Data with Django REST Framework

In this tutorial, you can learn how to use Django REST Framework serializers from Django MongoDB Extensions in your Django project.

Django MongoDB Extensions is a package that contains additional developer tools for Django MongoDB Backend. This tutorial shows you how to use the serializers in Django MongoDB Extensions to represent MongoDB-specific fields in your Django REST Framework API.

Note

Django REST Framework is available in Django MongoDB Extensions v0.3.0 and later.

Django MongoDB Extensions provides the following serializers in the django_mongodb_extensions.rest_framework module:

  • MongoModelSerializer: The top-level serializer for Django models that contain MongoDB-specific fields. Use this serializer instead of the Django REST Framework ModelSerializer for any model that uses ObjectIdAutoField. MongoModelSerializer automatically generates nested serializers for embedded fields.

  • EmbeddedModelSerializer: The serializer for EmbeddedModel classes. Because MongoModelSerializer handles embedded fields automatically, define an EmbeddedModelSerializer only when you want to customize how an embedded model is represented or when you need to write embedded data. Assign the subclass as an explicit field on the parent model's serializer.

  • PolymorphicEmbeddedModelSerializer: The serializer for polymorphic embedded fields. MongoModelSerializer applies this serializer automatically, so you don't reference it directly. Polymorphic embedded fields are read-only.

MongoModelSerializer automatically generates the correct Django REST Framework fields for the following MongoDB-specific field types:

  • ArrayField

  • EmbeddedModelField

  • EmbeddedModelArrayField

  • PolymorphicEmbeddedModelField (read-only)

  • PolymorphicEmbeddedModelArrayField (read-only)

  • ObjectIdField

  • ObjectIdAutoField

Before you begin this tutorial, create a Django project that uses Django MongoDB Backend. To create a project, see the Get Started with Django MongoDB Backend tutorial.

The following steps show how to install Django MongoDB Extensions and use its serializers to model movie data from MongoDB in your Django REST Framework API.

1

Run the following command to install Django MongoDB Extensions with the rest_framework dependency:

pip install "django-mongodb-extensions[rest_framework]"
2

Navigate to your project's settings.py file. Then, add "django_mongodb_extensions" and "rest_framework" to the INSTALLED_APPS setting, as shown in the following example:

INSTALLED_APPS = [
'django_mongodb_extensions',
'rest_framework',
# ... your other apps
]
3

In the Get Started tutorial, you created a models.py file that includes the following code:

from django.db import models
from django.conf import settings
from django_mongodb_backend.fields import EmbeddedModelField, ArrayField
from django_mongodb_backend.models import EmbeddedModel
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)
genres = ArrayField(models.CharField(max_length=100), null=True, blank=True)
class Meta:
db_table = "movies"
managed = False
def __str__(self):
return self.title
class Viewer(models.Model):
name = models.CharField(max_length=100)
email = models.CharField(max_length=200)
class Meta:
db_table = "users"
managed = False
def __str__(self):
return self.name

Ensure that your app directory contains this file. Then, create a serializers.py file in the same directory as your models.py file.

4

To serialize a model that uses ObjectIdAutoField, define a serializer that extends MongoModelSerializer in your serializers.py file. The following example defines a serializer for the Viewer model:

serializers.py
from django_mongodb_extensions.rest_framework import MongoModelSerializer
from .models import Viewer
class ViewerSerializer(MongoModelSerializer):
class Meta:
model = Viewer
fields = "__all__"
5

To serialize a field that stores an embedded model, define a serializer that extends EmbeddedModelSerializer for the embedded model, then reference it from the parent model's serializer.

To serialize the Movie model and its embedded Award model, update your serializers.py file to resemble the following:

serializers.py
from django_mongodb_extensions.rest_framework import (
MongoModelSerializer,
EmbeddedModelSerializer,
)
from .models import (
Viewer,
Award,
Movie,
)
class ViewerSerializer(MongoModelSerializer):
class Meta:
model = Viewer
fields = "__all__"
class AwardSerializer(EmbeddedModelSerializer):
class Meta:
model = Award
fields = "__all__"
class MovieSerializer(MongoModelSerializer):
awards = AwardSerializer()
class Meta:
model = Movie
fields = "__all__"

Note

Embedded Model Serializer Behavior

When you serialize an embedded model, note the following behavior:

  • EmbeddedModelSerializer excludes primary key fields unless you explicitly list them in Meta.fields.

  • The to_internal_value() method returns model instances rather than dictionaries.

  • You can't save embedded models directly. Save them through their parent models instead.

6

After you define a serializer, you can use it to convert a model instance into a dictionary of primitive data types that Django REST Framework can render as JSON.

Start a Python shell by running the following command:

python manage.py shell

Then, run the following code to query the sample_mflix.users collection for a viewer and serialize the result:

from sample_mflix.models import Viewer
from sample_mflix.serializers import ViewerSerializer
viewer = Viewer.objects.get(email="jason_momoa@gameofthron.es")
serializer = ViewerSerializer(viewer)
serializer.data

The data attribute contains the serialized representation of the viewer, which resembles the following output:

{'id': '...', 'name': 'Khal Drogo', 'email': 'jason_momoa@gameofthron.es'}
7

When you serialize a model that contains an embedded model, the serializer nests the embedded model's fields in the output.

From your Python shell, run the following code to query the sample_mflix.movies collection for a movie and serialize the result:

from sample_mflix.models import Movie
from sample_mflix.serializers import MovieSerializer
movie = Movie.objects.first()
serializer = MovieSerializer(movie)
serializer.data

The serialized output nests the awards embedded model inside the movie, which resembles the following:

{'id': '...',
'title': 'The Great Train Robbery',
'plot': 'A group of bandits stage a brazen train hold-up...',
'runtime': 11,
'released': '1903-12-01T00:00:00Z',
'awards': {'wins': 1, 'nominations': 0, 'text': '1 win.'},
'genres': ['Short', 'Western']}

Congratulations on completing the Django REST Framework tutorial! You now have a Django application that uses Django MongoDB Extensions serializers to represent MongoDB movie-related fields in a Django REST Framework API.

To learn more about Django REST Framework, see the Django REST Framework documentation.

To learn more about the Django MongoDB Extensions package, see django-mongodb-extensions on PyPI and the django-mongodb-extensions repository on GitHub.