title: How to bind different Mongoengine database aliases for Flask-Admin views?
body: <p>Developing a web admin interface for an information system using Flask-Admin and Mongoengine, I need Flask-Admin's <code>ModelView</code>s for all my entities. The system uses <strong>several MongoDB databases</strong>. Let's assume there's two of them for the sake of clarity.</p>
  
  <p>Normally, people manage such behavior using Mongoengine's <a href="http://docs.mongoengine.org/guide/connecting.html#multiple-databases" rel="nofollow noreferrer">database aliases</a>. During initialization, we define several aliases for our Flask app using Flask-Mongoengine's configuration:</p>
  
  <pre><code>    from mongoengine import DEFAULT_CONNECTION_NAME
      # Local packages
      from config import CurrentConfig  
  
      SECOND_DB_ALIAS = "second_db"
  
      app.config['MONGODB_SETTINGS'] = [
          {
              "ALIAS": DEFAULT_CONNECTION_NAME,
              "DB": CurrentConfig.DATABASE_NAME,
          },
          {
              "ALIAS": SECOND_DB_ALIAS,
              "DB": CurrentConfig.SECOND_DATABASE_NAME,
          },
      ]
  </code></pre>
  
  <p>Now we can use <code>Document</code>'s <code>meta</code> field, which binds the database (represented by its alias) to a particular entity:</p>
  
  <pre><code>    class Entity(Document):
          field = StringField()
  
          meta = {'db_alias': SECOND_DB_ALIAS}
  </code></pre>
  
  <p>Unfortunately, it doesn't suit my needs here, since <strong>the same entities (represented by the same <code>Document</code> class) can be present in both databases</strong>. I want to set the database I query against depending on the logic of the app.</p>
  
  <p>Well, whatever. We still can switch databases dynamically using Mongoengine's <a href="http://docs.mongoengine.org/guide/connecting.html#context-managers" rel="nofollow noreferrer">context managers</a>:</p>
  
  <pre><code>    with switch_db(Entity, SECOND_DB_ALIAS):
           Entity(field="value").save()
  </code></pre>
  
  <p>(Notice: unfortunately, it's <a href="https://github.com/MongoEngine/mongoengine/issues/788" rel="nofollow noreferrer">not thread-safe</a> at the moment of writing this question)</p>
  
  <p>That's what I do in the rest of the application. The problem is that <strong>I can't find a way to do the same in my Flask-Admin's <code>ModelView</code>s</strong>. How to set the alias of the database to query against in this situation?</p>
  
  <pre><code>    class EntityView(ModelView):
          can_delete = True
          can_edit = True
          can_view_details = True
          can_create = True
  
          can_export = True
  
          # No such or similar attribute!
          database_alias = SECOND_DB_ALIAS  
  
          def __init__(self):
              super().__init__(Entity, name="Entities")
  
      admin = Admin(app, name='Admin Panel', template_mode='bootstrap3')
      admin.add_view(EntityView())
  </code></pre>