美文网首页
mongodb如何使用在django中

mongodb如何使用在django中

作者: d33911380280 | 来源:发表于2017-08-30 15:03 被阅读330次

(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) 设置路由进行测试,


image.png

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

相关文章

网友评论

      本文标题:mongodb如何使用在django中

      本文链接:https://www.haomeiwen.com/subject/cbgzdxtx.html