【发布时间】:2015-10-14 07:42:23
【问题描述】:
是否可以使用变量作为集合名称的一部分,并根据mongoengine中的名称查询不同的集合?
例如:
我的 mongoDB 中有 3 个集合
- collection_first
- collection_second
- collection_third
并执行一个简单的 for 循环,例如:
collection_names = ['first', 'second', 'third']
for name in collection_names:
## Query the collection_+`name` here
对了,我在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')
非常感谢。
更新解决方案。
在models.py中定义模型,不带meta:
class Testing(DynamicDocument):
## Do NOT use the meta to point to a specific collection.
user_name = StringField(db_field='user_name')
调用函数时,使用switch_collection切换到真正的集合:
def search_in_testing(self, name, **kwargs):
with switch_collection(Testing, 'colection_%s' % (name)):
search_results = Testing.objects(**kwargs)
return search_results
在您的代码中,只需在 for 循环中调用函数:
collection_names = ['first', 'second', 'third']
for name in collection_names:
search_results = search_in_testing(name, name=name)
【问题讨论】:
标签: python django mongodb mongoengine