是否有可能使用变量作为集合名称的一部分并根据mongoengine中的名称查询不同的集合?通过mongoengine和Django中的不同变量查询不同的集合
例如:
有我的MongoDB 3个集
- collection_first
- collection_second
- collection_third
并执行一个简单的循环,如:
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模型,而不元:
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)
参考:switch_collection in mongoengine
你知道如何定义'model.py'在Django? –
mongoengine仍然不支持django我猜。我没有尝试过。我会研究一下,让你知道。 –
谢谢,我在0.90之前使用,它在该版本中支持Django。 –