Django + Mongo操作数据


Django里面配置mongoDB

一、settings.py里面配置

from mongoengine import connect
connect('connect_mongo_db')

二、models.py文件 配置models

import datetime

import mongoengine


class UUser(mongoengine.Document):
    name = mongoengine.StringField()
    uid = mongoengine.IntField()
    update_time = mongoengine.DateTimeField(default=datetime.datetime.now())

    def save(self, *args, **kwargs):
        """
        该方法为时间转换
        """
        if not self.update_time:
            self.update_time = datetime.datetime.now()
        self.update_time = datetime.datetime.now()
        return super(RankAsin, self).save(*args, **kwargs)

三、urls.py文件 配置路由

from django.conf.urls import url

from .views import *

urlpatterns = [
    url(r'^uuser/uuser/$', UUserView.as_view()),  # 新增
]

四、views 视图编写

import json

from rest_framework.response import Response
from rest_framework.views import APIView

from apps.子应用.models import UUser
from apps.子应用.utils import JSONEncoder
from utils.response_code import RET


class UUserView(APIView):

    def get(self, request):
        """
        获取数据 查询数据
        """
        name = request.GET.get('name') # 张三
        queryset = UUser.objects.filter(name="张三")

        # 原生to_json()返回格式为json
        # json_data = json.dumps(UUser.objects.filter(name=name))

        # 根据自定义返回的数据格式
        contentList = []
        for data in queryset:
            contentList.append({
                "id": json.loads(JSONEncoder().encode(data._id)),
                'name': data.name,
                'update_time': data.update_time.date(),
            })

        return Response({'code': RET.OK, 'data': contentList})

    def post(self, request):
        """
        创建数据
        """
        site = request.POST.get('site')
        u = request.POST.get('u') # 张三
        UUser.objects.create(name="张三")

        return Response({'code': RET.OK})

mongoDB 基本操作

方法 描述
DoesNotExist None
MultipleObjectsReturned None
cascade_save Recursively saves any references / generic references on an objects顺藤摸瓜式的保存所有被对象引用到的数据。就是保存EmbedDocument这种数据以及外键关联的数据。对象本身不做保存。如下:>>> t2= Test(name='Joe')>>> t2.cascade_save()>>> t2.reload().to_json()Traceback (most recent call last):File "<pyshell#121>", line 1, in <module>t2.reload().to_json()File "build\bdist.win-amd64\egg\mongoengine\document.py", line 457, in reloadraise self.DoesNotExist("Document does not exist")DoesNotExist: Document does not exist
clean Hook for doing document level data cleaning before validation is run. Any ValidationError raised by this method will not be associated with a particular field; it will have a special-case association with the field defined by NON_FIELD_ERRORS.
compare_indexes Compares the indexes defined in MongoEngine with the ones existing in the database. Returns any missing/extra indexes.对比mongoengine和数据库的索引。返回缺失/多余的索引。和ensure_index(es)配合使用。>>> t.ensure_index('name')u'name_1'>>> t.compare_indexes(){'extra': [[(u'name', 1)]], 'missing': []}
delete Delete the :class:~mongoengine.Document from the database. This will only take effect if the document has been previously saved.:param write_concern: Extra keyword arguments are passed down which will be used as options for the resultant getLastError command.For example, save(..., write_concern={w: 2, fsync: True}, ...) will wait until at least two servers have recorded the write and will force an fsync on the primary server.从数据库中删除mongoengine.Document实例。 之前调用了save方法才起作用。参数:write_concern: ...例如, save(..., write_concern={w:2, fsync:True},...) 的实际调用的时机: 至少有两个服务器执行了写操作,将会迫使主服务器执行fsync(同步)。>>> t2.delete()>>> t2.to_json()'{"_id": {"$oid": "54b71f7a4878c414e814d197"}, "name": "Tommy.yu"}'>>> t3=t2.reload()Traceback (most recent call last):File "<pyshell#93>", line 1, in <module>t3=t2.reload()File "build\bdist.win-amd64\egg\mongoengine\document.py", line 465, in reloadraise self.DoesNotExist("Document does not exist")DoesNotExist: Document does not exist
drop_collection Drops the entire collection associated with this :class:~mongoengine.Document type from the database.删除和mongoengine.Document子类关联的表(collection)。>>> t.drop_collection()>>> Test.objects.all()[]
ensure_index Ensure that the given indexes are in place. :param key_or_list: a single index key or a list of index keys (to construct a multi-field index); keys may be prefixed with a + or a - to determine the index ordering在mongoenging中加入索引。影响的是整个类的,不是实例的。直到整个collection被删除(drop_collection被调用)都有效。>>> t3=Test(name='John')>>> t3.compare_indexes(){'extra': [], 'missing': []}>>> t3.ensure_index('name')u'name_1'>>> t3.compare_indexes(){'extra': [[(u'name', 1)]], 'missing': []}
ensure_indexes Checks the document meta data and ensures all the indexes exist.Global defaults can be set in the meta - see :doc:guide/defining-documents .. note:: You can disable automatic index creation by setting auto_create_index to False in the documents meta data检查document的meta信息,并且确保所有的索引都存在于(mongoengine/db?)>>> class Test2(Document): name=StringField(max_length=100) url =StringField(max_length=100) meta={'indexes':['name','url']} >>> t2=Test2(name='Tommy.Yu', url='http://www.cnblogs.com/Tommy-Yu') >>> t2.ensure_indexes() >>> t2.compare_indexes() {'extra': [], 'missing': []} >>> t2.list_indexes() [[('name', 1)], [('url', 1)], [(u'_id', 1)]] >>> t2.drop_collection() >>> t2=Test2(name='Tommy.Yu', url='http://www.cnblogs.com/Tommy-Yu') >>> t2.list_indexes() [[('name', 1)], [('url', 1)], [(u'_id', 1)]] 实在是看不出来,看看数据库(经过测试,证实在save的时候已经创建了索引。索引对于性能的提升很夸张,看这里。):> db.test2.getIndexes()[{"v" : 1,"key" : {"_id" : 1},"name" : "_id_","ns" : "local.test2"},{"v" : 1,"key" : {"name" : 1},"name" : "name_1","ns" : "local.test2","background" : false,"dropDups" : false},{"v" : 1,"key" : {"url" : 1},"name" : "url_1","ns" : "local.test2","background" : false,"dropDups" : false}]  无法确定这个函数干嘛了。
from_json 将json数据转化为未保存的documeng对象。>>> b= t.from_json('{"name":"joe"}')>>> t.to_json()'{"_id": {"$oid": "54b6353c4878c414e814d195"}, "name": "Tommy.Yu"}'>>> b.to_json()'{"name": "joe"}'
list_indexes Lists all of the indexes that should be created for given collection. It includes all the indexes from super- and sub-classes.列举出表(collection)的所有索引。包含父类和子类的!>>> t.list_indexes()[[(u'_id', 1)]]
my_metaclass Metaclass for top-level documents (i.e. documents that have their own collection in the database.
register_delete_rule This method registers the delete rules to apply when removing this object.
reload 从数据库重新加载所有属性>>> a=t.reload()>>> a is tFalse>>> a<Test: Test object>>>> a.to_json()'{"_id": {"$oid": "54b6353c4878c414e814d195"}, "name": "Tommy.Yu"}'
save >>>u.save()<Test: Test object>源码在这里。保存 Document到数据库. 存在则修改,否则插入。参数force_insert – 不管数据是否存在,强制插入。默认为Falsevalidate – 是否验证输入数据,默认为True; clean – 是否调用clean方法,需要validate参数为True。默认为True。write_concern – Extra keyword arguments are passed down to save() OR insert() which will be used as options for the resultant getLastErrorcommand. For example, save(..., write_concern={w: 2, fsync: True}, ...) will wait until at least two servers have recorded the write and will force an fsync on the primary server.cascade – 是否级联保存。可以在meta(class Meta)中设置这个属性,默认为None.cascade_kwargs – (可选) 传递给级联保存函数(cascade_save)的字典型参数。需要 cascade参数为True,默认为None._refs – A list of processed references used in cascading saves。传递给级联保存函数的(已处理的?)引用列表。默认为None.save_condition – only perform save if matching record in db satisfies condition(s) (e.g., version number)。只有条件符合时,才保存数据。默认为None.
select_related Handles dereferencing of :class:~bson.dbref.DBRef objects to a maximum depth in order to cut down the number queries to mongodb. .. versionadded:: 0.5>>> t.select_related()<Test: Test object>>>> t.select_related(2)<Test: Test object>
switch_collection Temporarily switch the collection for a document instance. Only really useful for archiving off data and calling save():: user = User.objects.get(id=user_id) user.switch_collection('old-users') user.save() If you need to read from another database see :class:~mongoengine.context_managers.switch_db :param collection_name: The database alias to use for saving the document
switch_db Temporarily switch the database for a document instance. Only really useful for archiving off data and calling save():: user = User.objects.get(id=user_id) user.switch_db('archive-db') user.save() If you need to read from another database see :class:~mongoengine.context_managers.switch_db :param db_alias: The database alias to use for saving the document
to_dbref Returns an instance of :class:~bson.dbref.DBRef useful in __raw__ queries.返回bson.dbref.DBRef的实例。在'raw'查询时比较有用(pyMongo?)>>>t.to_dbref()DBRef('test', ObjectId('54b6353c4878c414e814d195'))
to_json 转换成json对象>>>t.to_json()'{"name": "Tommy.Yu"}'
to_mongo Return as SON data ready for use with MongoDB.>>> t.to_mongo()SON([('_id', ObjectId('54b6353c4878c414e814d195')), ('name', u'Tommy.Yu')])
update Performs an update on the :class:~mongoengine.Document A convenience wrapper to :meth:~mongoengine.QuerySet.update. Raises :class:OperationError if called on an object that has not yet been saved.在mongoengine.Document类上进行更新操作。方法 mongoengine.QuerySet.update的简单包装。如果对象尚未调用save方法,会触发OperationError异常。ps:源码。加入upsert参数是删除所有字段>>> t.to_json()'{"_id": {"$oid": "54b71e044878c414e814d196"}, "name": "Tommy.Yu"}'>>> t.name='Tommy'>>> t.update(upsert=True)1>>> t.to_json()'{"_id": {"$oid": "54b71e044878c414e814d196"}, "name": "Tommy"}'>>> t2=t.reload()>>> t2.to_json()'{"_id": {"$oid": "54b71e044878c414e814d196"}}'>>> t.save()<Test: Test object>>>> t.to_json()'{"_id": {"$oid": "54b71e044878c414e814d196"}}'  更新字段需要在栏位前面加入set,如下:`>>> t.update(setname='joe')1>>> t.reload()<Test: Test object>>>> t.to_json()'{"_id": {"$oid": "54b6353c4878c414e814d195"}, "name": "joe"}'`
validate Ensure that all fields' values are valid and that required fields are present.


文章作者: 柒仔
文章链接: /article/36/
版权声明: 本博客所有文章除特別声明外,均采用 CC BY 4.0 许可协议。转载请注明来源 XiaoLiu!
侵权声明: 若无意对您的文章造成侵权,请您留言,博主看到后会及时处理,谢谢。
评论-----昵称和邮箱必填,网址选填
  目录