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

是否可以使用变量作为集合名称的一部分,并根据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')

非常感谢你.

更新解决方案.

在不使用meta的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

最佳答案 也许这个
commit中的以下测试在某种程度上会有所帮助:

def test_dynamic_collection_naming(self)
      def create_collection_name(cls):
          return "PERSON"

      class DynamicPerson(Document): 
          name = StringField()
          age = IntField()

          meta = {'collection': create_collection_name}

      collection = DynamicPerson._get_collection_name()
      self.assertEquals(collection, 'PERSON') 
      DynamicPerson(name='Test User', age=30).save()  
      self.assertTrue(collection in self.db.collection_names())
点赞