在mongoengine和Django中通过不同变量查询不同集合

Jim*_*Lin 5 python django mongodb mongoengine

是否可以使用变量作为集合名称的一部分并根据mongoengine中的名称查询不同的集合?

例如:

我的mongoDB中有3个集合

  • 收藏优先
  • 集合_秒
  • 集合_第三

并执行一个简单的 for 循环,例如:

collection_names = ['first', 'second', 'third']
for name in collection_names:
    ## Query the collection_+`name` here
Run Code Online (Sandbox Code Playgroud)

顺便问一下,我在Django中使用mongoengin,这种场景的model.py如何设置?

class Testing(DynamicDocument):
    # The collection_name should be dynamic, isn't it?
    meta = {'collection' : 'collection_name'}         
    user_name = StringField(db_field='user_name')
Run Code Online (Sandbox Code Playgroud)

非常感谢。


更新解决方案。

在 models.py 中定义不带元数据的模型:

class Testing(DynamicDocument):
    ## Do NOT use the meta to point to a specific collection.
    user_name = StringField(db_field='user_name')
Run Code Online (Sandbox Code Playgroud)

调用该函数时,使用switch_collection切换到真正的集合:

def search_in_testing(self, name, **kwargs):
    with switch_collection(Testing, 'colection_%s' % (name)):
        search_results = Testing.objects(**kwargs)
    return search_results
Run Code Online (Sandbox Code Playgroud)

在您的代码中,只需在 for 循环中调用该函数:

collection_names = ['first', 'second', 'third']
for name in collection_names:
    search_results = search_in_testing(name, name=name)
Run Code Online (Sandbox Code Playgroud)

参考:mongoengine中的switch_collection

sal*_*hed 0

是的,你可以这样做。举个例子,

for name in collection_names:
    for doc in db[collection_+'name'].find():
        print doc
Run Code Online (Sandbox Code Playgroud)

这里的 db 是Database对象。