V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
billion
V2EX  ›  Python

mongoengine 如何使用 xxx[yyy].object()的形式获取数据?

  •  
  •   billion ·
    kingname · 2016-01-03 16:13:17 +08:00 · 2336 次点击
    这是一个创建于 3051 天前的主题,其中的信息可能已经有所发展或是发生改变。

    当我们使用 pymongo 的时候,可以使用下面的方式连接到 example 数据库中的名叫 col 的集合中:

    conn = pymongo.MongoClient()
    db = conn.example
    collection = db.col
    

    当然也可以使用如下的代码,他们的作用是完全一样的。

    dbname = 'example'
    collectionName = 'col'
    conn = pymongo.MongoClient()
    db = conn[dbname]
    connection = db[collectionName]
    

    但是现在我使用 mongoengine, 假设我在数据库中有一个集合叫做 collectionA, 然后在 model.py 文件中有这样一个类:

    class collectionA(Document):
        A=StringField()
        B= StringField()
    

    所以我就可以使用

    import model
    x = model.collectionA.object(A='xxx')
    

    来查询数据

    由于有很多的集合,所以我希望是用

    model[collectionName].object(A='xxx ')
    

    来查询数据,但是我发现 mongoengin 似乎不支持这种方式.

    所以我想请问一下是不是我的用法不对,以及应该如何修改。我确实不想写几十个 if - elif 。感谢!

    2 条回复    2016-01-03 20:06:05 +08:00
    janxin
        1
    janxin  
       2016-01-03 19:18:30 +08:00
    是不支持的
    Drifter
        2
    Drifter  
       2016-01-03 20:06:05 +08:00
    Of course, this is not support.

    为什么要定义 Document ,就是为了将数据库中的 collection 与 python 中定义的 class 映射。
    而 pymongo 可以是因为直接将 collection 取出来作了[{}]这样的基本数据结构。

    你当然需要定义好你这边的 document ,才能让 mongoengine 找到映射的 collection ,再转成对应的 document 。
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   1806 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 16:44 · PVG 00:44 · LAX 09:44 · JFK 12:44
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.