Search code examples
python-3.xflaskassociationsflask-sqlalchemyflask-admin

How to: Display / Edit association_proxy columns in flask_admin


Yes, I have seen this question and have read about as much of the flask_admin documentation as I can stomach. That said, it's all very dense, and I am at a loss for what seems like a simple problem.

Code:

Models (app/models.py)

# Define the models for Paper and Keywords, with intermediary KeywordPaper
# Allows convenience of Paper.keywords += ["keyword"]

class Paper(db.Model):
    # ...
    keywords = association_proxy('paper_keywords', 'keyword',
                                 creator=lambda kw: Keyword(keyword=kw))
    # ...

class KeywordPaper(db.Model):
    # ...
    keyword_id = db.Column(db.Integer,
                           db.ForeignKey('keywords.id'),
                           primary_key=True)
    paper_id = db.Column(db.Integer,
                         db.ForeignKey('papers.id'),
                         primary_key=True)
    keyword = db.relationship(Keyword, lazy='joined')
    paper = db.relationship('Paper',
                            backref=db.backref("paper_keywords",
                                               cascade="all, delete-orphan"))
    # ...

class Keyword(db.Model):
    # ...
    id = db.Column(db.Integer, primary_key=True)
    keyword = db.Column(db.String(50))
    # ...

Model View (app/auth/model_views.py)

class MainModelView(ModelView):
    # ...
    form_base_class = SecureForm
    # ...

class PaperModelView(MainModelView):
    page_size = 20
    column_list = (
        # ...
        'keywords',
        # ...
    )
    column_searchable_list = (
        # ...
        'keywords',
        # ...
    )
    column_editable_list = (
        # ...
        'keywords',
        # ...
    )
    form_ajax_refs = {
        # ... keywords here?
    }
    # ...

app/auth/__init__.py

# ...
auth = Blueprint('auth', __name__)
from . import views
auth.model_views = []
# ...
paper_model_view = PaperModelView(Paper, db.session)
auth.model_views += [paper_model_view]
# ...
from . import forms
# ...

app/__init__.py

def create_app(config_name):
    # ...
    with app.app_context():
        # ...
        # Initialize auth blueprint
        from .auth import auth as auth_blueprint
        app.register_blueprint(auth_blueprint)
        # Add model vies to the admin console (again, with app context)
        admin.add_views(*auth_blueprint.model_views)

    return(app)

Current Result

Association Proxy column is blank :(


Solution

  • Hey anyone reading this...

    Using an association proxy turned out to be a lot of work for no reason when using flask admin. So, I just converted the keyword relationship to a normal many-to-many relationship. So, problem solved I guess.