1

如何在 couchdb-python 中执行 ViewField 中定义的 map 函数

>>> from couchdb import Server
>>> from couchdb.mapping import Document, TextField, IntegerField, DateTimeField, ViewField
>>> db = server.create('python-tests')

>>> class Person(Document):
...     _id = TextField()                    
...     name = TextField()                  
...     age = IntegerField()                
...     by_name = ViewField('people', '''\  
...             function(doc) {             
...                     emit(doc.name, doc);
...             }''')
... 
>>> person = Person(_id='Person1', name='John Doe', age=42)                                
>>> person.store(db)                                                                       
<Person u'Person1'@u'1-95aa43bc1639f0602812ef78deca0a96' {'age': 42, 'name': u'John Doe'}>
>>> Person.by_name(db)
<ViewResults <PermanentView '_design/people/_view/by_name'> {}>


>>> for row in db.query(Person.by_name(db)):
...     print row.key
... 
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "/home/mit/apps/pymodules/lib/python2.7/site-packages/CouchDB-0.9-py2.7.egg/couchdb/client.py", line 713, in query
wrapper=wrapper)(**options)
  File "/home/mit/apps/pymodules/lib/python2.7/site-packages/CouchDB-0.9-py2.7.egg/couchdb/client.py", line 1041, in __init__
self.map_fun = dedent(map_fun.lstrip('\n\r'))
AttributeError: 'ViewResults' object has no attribute 'lstrip'
4

2 回答 2

1

您可以使用 map 函数作为第一个参数调用查询方法:

for row in db.query(Person.by_name.map_fun):
    print row.key

查找查询方法签名

于 2014-04-19T21:06:08.823 回答
1

不要忘记将 design_doc 与 ViewField 映射一起存储。为此,请调用 sync() :

Person.by_name.sync(db)

之后您将能够使用这样的视图:

for person in Person.by_name(db):
     print person._id

我在包的文档中没有任何参考。查看 python shell 中 ViewDefinition Class 的文档字符串或代码源https://github.com/oliora/couchdb-python/blob/master/couchdb/design.py

于 2015-07-21T22:01:48.637 回答