mongodb如何使用在django中

(1)创建新项目,用于测试。

django-admin.py startproject mongodbtest
cd mongodbtest
 python manage.py startapp station

(2)在setting.py的INSTALLED_APPS中加入如下应用

image.png

添加以下代码进行数据库连接

from mongoengine import connect  
connect('xunjian')  

(3) 建立模型,以简单的station为例,要使用mongoengine.Document

from __future__ import unicode_literals
from mongoengine import Document, StringField

class Station(Document):  
    name = StringField(max_length=50)  
    code = StringField(max_length=50)  
    def __unicode__(self):
        return self.name

(4) 对serializer需要稍作变化,使用rest_framework_mongoengine.serializers

from rest_framework_mongoengine import serializers
from . import models

class StationSerializer(serializers.DocumentSerializer):
    class Meta:
        model = models.Station
        fields = ('name', 'code')

(5) 在view中同理,

from . import models
from . import serializers
from rest_framework_mongoengine import generics
class StationListView(generics.ListCreateAPIView):
    queryset = models.Station.objects.all()
    serializer_class = serializers.StationSerializer

(6) 设置路由进行测试,


mongodb如何使用在django中_第1张图片
image.png

注:rest_framework_mongoengine的api详见http://umutbozkurt.github.io/django-rest-framework-mongoengine/index.html

你可能感兴趣的:(mongodb如何使用在django中)