是否有可能使用變量作爲集合名稱的一部分並根據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。 –