Request a different collection for different variables in mongoengine and Django

Is it possible to use a variable as part of the collection name and request another collection based on the name in mongoengine?

For example:

There are 3 collections in my mongoDB

  • collection_first
  • collection_second
  • collection_third

and do a simple for loop, for example:

collection_names = ['first', 'second', 'third']
for name in collection_names:
    ## Query the collection_+`name` here

By the way, I am using mongoengin in Django, how to install model.py of such a script?

class Testing(DynamicDocument):
    # The collection_name should be dynamic, isn't it?
    meta = {'collection' : 'collection_name'}         
    user_name = StringField(db_field='user_name')

Many thanks.


Update solution.

Define the model in models.py without meta:

class Testing(DynamicDocument):
    ## Do NOT use the meta to point to a specific collection.
    user_name = StringField(db_field='user_name')

When you call a function, use switch_collectionto switch to the real collection:

def search_in_testing(self, name, **kwargs):
    with switch_collection(Testing, 'colection_%s' % (name)):
        search_results = Testing.objects(**kwargs)
    return search_results

In your code, just call the function in a for loop:

collection_names = ['first', 'second', 'third']
for name in collection_names:
    search_results = search_in_testing(name, name=name)

Link: switch_collection in mongoengine

+4
2

, 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())
+1

, . ,

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

db - Database.

0

Source: https://habr.com/ru/post/1611561/


All Articles