最近,我开始使用Mongo DB作为我的一个项目的数据库。
我按照不同网站上的说明配置Django使用Mongo作为数据库。但是,说明并不清楚。
所以,在这篇文章中,我想列出我为安装所需的软件包,配置Django,创建一个简单的应用程序以及验证操作以创建文档和列出所有文档所遵循的步骤
我的环境是使用Python 3.6.5的Ubuntu 16.04
安装所需的包
apt install python3-pip
pip3 install django == 1.11
pip3 install djangorestframework
pip3 install django-rest-framework-mongoengine
pip3 install pymongo
pip3 install mongoengine
创建一个Django项目和应用程序
django-admin startproject mysite
cd mysite
python manage.py startapp polls
配置项目设置
mysite/settings.py
INSTALLED_APPS = [
'rest_framework',
'polls.apps.PollsConfig',
#default apps
]
# Set database settings to None
DATABASES = {
'default': {
'ENGINE': '',
}
}
# Configure Mongo as database. Replace below values as required
from mongoengine import connect
MONGO_DATABASE_NAME = 'testdb'
MONGO_HOST = '127.0.0.1'
MONGO_PORT = 27017
connect(MONGO_DATABASE_NAME, host=MONGO_HOST, port=MONGO_PORT)
配置项目url
from django.conf.urls import url, include
urlpatterns = [
url(r'^polls/', include('polls.urls')),
]
配置应用模型
polls/models.py
from mongoengine import Document, fields
class Poll(Document):
poll_name = fields.StringField(required=True)
poll_votes = fields.IntegerField(required=True)
配置应用序列化程序
polls/serializers.py
from rest_framework_mongoengine import serializers
from .models import Poll
class PollSerializer(serializers.DocumentSerializer):
class Meta:
model = Poll
fields = '__all__'
配置应用视图
polls/views.py
from rest_framework import status
from rest_framework.views import APIView
from rest_framework.response import Response
from .models import Poll
from .serializers import PollSerializer
class PollView(APIView):
def get(self, request):
serializer = PollSerializer(Poll.objects.all(), many=True)
response = {"polls": serializer.data}
return Response(response, status=status.HTTP_200_OK)
def post(self, request, format=None):
data = request.data
serializer = PollSerializer(data=data)
if serializer.is_valid():
poll = Poll(**data)
poll.save()
response = serializer.data
return Response(response, status=status.HTTP_200_OK)
配置应用url
polls/urls.py
from django.conf.urls import url
from . import views
urlpatterns = [
url(r'^$', views.PollView.as_view()),
]
启动Django开发服务器
python manage.py runserver
验证2个API以创建轮询并列出所有民意调查
curl -H 'Accept: application/json; indent=4' http://127.0.0.1:8000/polls/
curl -H "Content-Type: application/json" -X POST -d '{"poll_name": "Elections","poll_votes": 100}' http://127.0.0.1:8000/polls/
注意:
- 我们不需要像其他类型的数据库一样同步表;
- 在MongoDB中创建的集合的名称将是模型类的小写名称(上例中的轮询。因此,该集合将命名为poll)。