引言:
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到數據庫. 存在則修改,否則插入。
|
||
| 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. |
