Overview
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.
Serializers
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
ModelSerializerfor any model that usesObjectIdAutoField.MongoModelSerializerautomatically generates nested serializers for embedded fields.EmbeddedModelSerializer: The serializer for
EmbeddedModelclasses. BecauseMongoModelSerializerhandles embedded fields automatically, define anEmbeddedModelSerializeronly 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.
MongoModelSerializerapplies 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:
ArrayFieldEmbeddedModelFieldEmbeddedModelArrayFieldPolymorphicEmbeddedModelField(read-only)PolymorphicEmbeddedModelArrayField(read-only)ObjectIdFieldObjectIdAutoField
Prerequisites
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.
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.
Set up your files.
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.
Serialize a model.
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:
from django_mongodb_extensions.rest_framework import MongoModelSerializer from .models import Viewer class ViewerSerializer(MongoModelSerializer): class Meta: model = Viewer fields = "__all__"
Serialize an embedded model.
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:
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:
EmbeddedModelSerializerexcludes primary key fields unless you explicitly list them inMeta.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.
View the serialized output of a model.
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'}
View the serialized output of an embedded model.
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']}
Next Steps
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.