Table of Contents
- 1 Introduction
- 2 Preparation
- 3 Django Install
- 4 Install Django REST Framework
- 5 Install django-rest-framework-mongoengine Dependencies
- 6 Install MongoDb service (on Mac) with Homebrew
- 7 Inform the Database for mongoengine and django
- 8 Create your Models
- 9 Create the Serializers
- 10 Create the Views
- 11 Create Routes
- 12 Test your Application
Introduction
Sometimes you, as software engineer, identifies the need for a non-relational database. Nowadays the most common NoSQL database is Mongo.
In this post i will demonstrate how to add MongoDb (mongoengine) into a Django Rest Framework setup.
If you want to know how to install Django Framework with Django Rest Framework, refer to this post: Creating a Rest API/Webservice with Django Rest Framework and MYSQL using Python 3
The complete code for this tutorial is in my github, here: https://github.com/fernandorodriguespro/rest-api-django-drf-mongo
Preparation
Create the project directory e cd into it
mkdir project-name && cd project-name
Create a virtualenv to isolate our package dependencies locally, and activate the virtual environment
virtualenv -p python3 env && source env/bin/activate
Django Install
Install Django into the virtualenv
pip3 install django
Set up a new project and cd into it
# Note the trailing '.' character django-admin.py startproject project . && cd project
Define a single application for this project
django-admin.py startapp appname && cd ..
Add the created App to INSTALLED_APPS in settings.py, using your favorite IDE
INSTALLED_APPS = [ #... 'project.appname' ]
Remove the default database engine that is automatically set for you. By default Django adds the SQLite, we don’t want that. Remove the definitions from DATABASES in settings.py. It should look like this, after you remove the default key:
DATABASES = { }
Test if the App is working
python3 manage.py runserver
Go to http://localhost:8000/ to check if you see a Welcome page.
Install Django REST Framework
Install it using PIP3
pip3 install djangorestframework
Declare it in INSTALED_APPS on settings.py
INSTALLED_APPS = [ #... 'rest_framework' ]
Install django-rest-framework-mongoengine Dependencies
pip3 install mongoengine
pip3 install django-rest-framework-mongoengine
Install MongoDb service (on Mac) with Homebrew
For alternate os versions: https://docs.mongodb.com/manual/administration/install-community/
Installing MongDb
brew update
brew install mongodb
Running MongoDb
Create the data directory
mkdir -p /data/db
Make sure that the user running the mongod process, has read and write permissions for this folder.
Test if the server is ok
mongod
If everything is ok, you should see something like this in a terminal
2018-01-09T22:18:03.471-0200 I FTDC [initandlisten] Initializing full-time diagnostic data capture with directory '/data/db/diagnostic.data'2018-01-09T22:18:03.471-0200 I NETWORK [initandlisten] waiting for connections on port 21017
Theres no need to create a database using mongo shell, because “when you first store data in the database, such as by creating a collection, MongoDB creates the database”. From: https://docs.mongodb.com/manual/mongo/
Inform the Database for mongoengine and django
In the Django App settings.py add the database connection information
import mongoengine mongoengine.connect( db="tools", host="localhost" )
Create your Models
Here is a sample on how to create a Model
# project/appname/models.py from mongoengine import Document, EmbeddedDocument, fields class ToolInput(EmbeddedDocument): name = fields.StringField(required=True) value = fields.DynamicField(required=True) class Tool(Document): label = fields.StringField(required=True) description = fields.StringField(required=True, null=True) inputs = fields.ListField(fields.EmbeddedDocumentField(ToolInput))
Create the Serializers
Create the serializers.py inside your app and add the following content
from rest_framework_mongoengine import serializers from project.appname.models import Tool class ToolSerializer(serializers.DocumentSerializer): class Meta: model = Tool fields = '__all__'
Create the Views
This is a pure rest-framework-mongoengine, you will probably have more rest-framework only imports and definitions
from django.shortcuts import render from rest_framework_mongoengine import viewsets as meviewsets from project.appname.serializers import ToolSerializer from project.appname.models import Tool class ToolViewSet(meviewsets.ModelViewSet): lookup_field = 'id' queryset = Tool.objects.all() serializer_class = ToolSerializer
Create Routes
To accomplish this first create a urls.py file inside the project/appname, this one is a “chid” url set
from django.conf.urls import url from rest_framework_mongoengine import routers as merouters from project.appname.views import ToolViewSet merouter = merouters.DefaultRouter() merouter.register(r'mongo', ToolViewSet) urlpatterns = [ ] urlpatterns += merouter.urls
Inform the project that this new url set exist. In the project/urls.py (the parent), add the child, like this:
from django.contrib import admin from django.urls import path from django.conf.urls import url, include urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^api/', include('project.appname.urls')), ]
Test your Application
Run the server
python3 manage.py runserver
Test connection to the server using you favorite tool, i use Postman. If everything here has been applied and the mongod service is up, everything should work right.
Sources:
https://github.com/umutbozkurt/django-rest-framework-mongoengine
https://docs.mongodb.com/manual/
https://medium.com/@vasjaforutube/django-mongodb-django-rest-framework-mongoengine-ee4eb5857b9a
Leonardo Castro
November 11, 2018Hello, could you please post the packages versions.
Arturo
November 25, 2018Hi Fernando!
This tutorials is helping me a lot in order to develop my own django rest app.
I need to authenticate users, so I want to declare my custom User model.
Do you think that it’s fine to use mongondb in this case?
Juan
December 17, 2018Everything worked fine and smooth! Thank you.
ravi
June 20, 2019I read this tutorial and find very useful. can you please help me on that how to implement the aggregate function in django