引言:

from mongoengine import *
connect('local')
class Test(Document):
name=StringField(max_length=32) t = Test(name='Tommy.Yu')

  

方法 描述
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 reload
raise 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 reload
raise 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 t
False
>>> a
<Test: Test object>
>>> a.to_json()
'{"_id": {"$oid": "54b6353c4878c414e814d195"}, "name": "Tommy.Yu"}'
save
>>>u.save()
<Test: Test object>

源码在这里

保存 Document到数据库. 存在则修改,否则插入。

参数
  • force_insert – 不管数据是否存在,强制插入。默认为False
  • validate – 是否验证输入数据,默认为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 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.

  • 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(set__name='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.

浅析mongoEngine的document对象的更多相关文章

  1. 报表软件JS开发引用HTML DOM的location和document对象

    上一次提到,在报表软件FineReport的JavaScript开发中,可以访问并处理的HTML DOM对象有windows.location.document三种.这次就继续介绍后两种,locati ...

  2. Document对象和window对象

    window对象--- 代表浏览器中的一个打开的窗口或者框架,window对象会在<body>或者<frameset>每次出现时被自动创建,在客户端JavaScript中,Wi ...

  3. Window.document对象

    1.Window.document对象 一.找到元素: docunment.getElementById("id"):根据id找,最多找一个:     var a =docunme ...

  4. JavaScript的DOM操作。Window.document对象

    间隔执行一段代码:window.setlnteval("需要执行的代码",间隔毫秒数) 例 :      window.setlnteval("alert("你 ...

  5. HTML DOM Document 对象

    HTML DOM Document 对象 HTML DOM 节点 在 HTML DOM (Document Object Model) 中 , 每一个元素都是 节点: 文档是一个文档. 所有的HTML ...

  6. JS中document对象和window对象有什么区别

    简单来说,document是window的一个对象属性.Window 对象表示浏览器中打开的窗口.如果文档包含框架(frame 或 iframe 标签),浏览器会为 HTML 文档创建一个 windo ...

  7. 9.22 window对象、document对象

    一.window对象: 属性(值或者子对象): opener:打开当前窗口的源窗口,如果当前窗口是首次启动浏览器打开的,则opener是null,可以利用这个属性来关闭源窗口 dialogArgume ...

  8. Window.document对象 轮播练习

    Window.document对象 一.找到元素:     docunment.getElementById("id"):根据id找,最多找一个:     var a =docun ...

  9. javascript获取iframe框架中页面document对象,获取子页面里面的内容,iframe获取父页面的元素,

    javascript获取iframe框架中,加载的页面document对象 因为浏览器安全限制,对跨域访问的页面,其document对象无法读取.设置属性 function getDocument(i ...

随机推荐

  1. UnityShader:HSV(色相,饱和度,亮度)转换

    http://blog.csdn.net/costfine/article/details/46930473 发现其实美术调整颜色的时候大部分都是调整的HSV,因为可以方便的分别调整色相(hue).饱 ...

  2. OpenGL瓶颈

    在优化Erya3D引擎的过程中,遇到的瓶颈: 1. 字符串操作,避免逐个字符的比较,使用哈希码比较2. 贴图操作:切换绑定贴图.更改贴图参数3. 切换绑定GLSL程序4. Draw Call:http ...

  3. PHP数组处理函数的使用array_push(一)

    使用PHP做数据处理时会涉及到大量的数组操作,这里我就记下各种数组处理函数的使用方法,好记性不如烂笔头!! 一.array_push的使用方法:将一个或多个单元压入数组的末尾(入栈) 说明:int a ...

  4. 30 分钟开发一个简单的 watchOS 2 app <oneVcat>

    Apple Watch 和 watchOS 第一代产品只允许用户在 iPhone 设备上进行计算,然后将结果传输到手表上进行显示.在这个框架下,手表充当的功能在很大程度上只是手机的另一块小一些的显示器 ...

  5. [C#]集合已修改;可能无法执行枚举操作

    摘要 我相信很多人对这个再熟悉不过了.对已经修改的集合进行操作就会出现这个错. 解决办法 比如有下面的一段代码,我们创建一个集合,并向集合中添加10个数,然后,我们循环再将这些数移除了. static ...

  6. linux下定时执行任务方法【转】

     之前就转过一篇关于定时任务的文章,前俩天用,还的翻出来看!!!再转一次,备用,,需要的时候不用麻烦找! ----------------------------------------------- ...

  7. php:Header

    转自鸟哥的博客: http://www.laruence.com/2007/12/16/308.html PHP header()the function declaration: void head ...

  8. php 冒泡排序

    public function demo($arr){ $len = count($arr); if ($len == 1) { return $arr; } else { for ($i = 1; ...

  9. 有利于SEO优化的DIV+CSS的命名规则小结

    可以先去这里温习一下CSS和HTML的知识!DIV+CSS规范命名大全集合  CSS开发技巧整理 一.CSS文件及样式命名 1.CSS文件命名规范 全局样式:global.css/master.css ...

  10. oracle中session的查询与删除

    1. 查询连接的session select sid,serial#,username,program,machine,status from v$session 查询的结果如下,可以根据机器和登录的 ...