【问题标题】:Query different collection by different variable in mongoengine and Django在 mongoengine 和 Django 中通过不同的变量查询不同的集合
【发布时间】: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)

参考:switch_collection in mongoengine

【问题讨论】:

    标签: python django mongodb mongoengine


    【解决方案1】:

    也许这个 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())
    

    【讨论】:

      【解决方案2】:

      是的,你可以这样做。例如,

      for name in collection_names:
          for doc in db[collection_+'name'].find():
              print doc
      

      这里的 db 是 Database 对象。

      【讨论】:

      • 你知道如何在django中定义model.py吗?
      • mongoengine 我猜仍然不支持 django。我没试过。我会研究一下,然后告诉你。
      • 谢谢,我用的是0.90之前的版本,支持django。
      • 您好,我找到了解决问题的方法,如果您有兴趣,请查看我的更新。
      猜你喜欢
      • 2011-03-19
      • 2022-01-23
      • 2021-05-10
      • 2015-04-09
      • 1970-01-01
      • 2012-01-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多